これは仮想関数と関係していると確信していますが、どうやって解決するかは苦労しています。ここでC++クラス - 使用するクラスに関数を渡すにはどうすればよいですか?
私(簡体字)の状況である:あり
は大体何プログラムはありませんが、ファイル(computer.h)空白の画面とコンピューターを描くのペアを持っているし、別のペア(program.hは)
:コンピュータクラスは、多くの異なる状況で再利用されようとしているので、画面の描画機能がcomputer.h
で一般的な方法
に渡す必要があり、そのコンピュータの画面上に描画する
を必要とする機能 で
:
program.h
で
void computer::drawComputer(){
//draws all the components then the monitor
drawMonitor(); //this is where the external function (from class screen) needs to execute
}
void computer::drawMonitor(){
//draws the background and border of screen
}
:
program.cpp
で
class program {
//many other program functions
void drawScreen();
};
:
//many other program functions
void program::drawScreen(){
//this function draws the contents of the screen
}
私の質問、program.cpp
から、どのように私は '送信' んさdrawScreen()
機能内で実行するはcomputer.cpp
で機能しますか?私はそれを実装しようとすると
編集
@クリスのソリューションは、私が後だものをほぼ正確であるように思わは、しかし、私は、次のエラーを取得:
testApp.h:40: error: 'testApp::prog' cannot appear in a constant-expression
testApp.h:40: error: `&' cannot appear in a constant-expression
testApp.h:40: error: a cast to a type other than an integral or enumeration type cannot appear in a constant-expression
testApp.h:40: error: ISO C++ forbids initialization of member 'isprog'
testApp.h:40: error: making 'isprog' static
testApp.h:40: error: invalid in-class initialization of static data member of non-integral type 'IScreen*'
testApp.h:41: error: 'isprog' has not been declared
testApp.h:42: error: ISO C++ forbids declaration of 'comp1' with no type
testApp.h:42: error: expected ';' before '.' token
行が
です39 Program prog;
40 IScreen *isprog = dynamic_cast<IScreen*>(&prog);
41 OP1 comp1(isprog);
42 comp1.drawScreen();
誰がどこで実装が間違っているのか知っていますか?
ありがとう@クリス、私は後になっているように見えるthats。私の 'program'クラスがすでに別のクラスを継承しているので、'抽象型のオブジェクトを割り当てることができません 'testApp''エラー –
問題を解決しました - 私は十分実装していませんでした。今度はうまくコンパイルされますが、 'myScreen-> drawScreen();'行に 'EXEC_BAD_ACCESS'エラーでクラッシュします。これは間違ったメモリチャンクにアクセスするエラーです。何か案は? –
関連するコード( 'Program'の割り当て方法を含む)がなければ私はコメントできません。 1つの可能性は、「myScreen」が指しているものが削除されていることです(しかし、それは暗闇の中で完全に刺すことです)。 –