クラスの前方宣言は「class ClassName;」となると思いますが、メンバ関数を前方宣言したい場合は、どのように書けばいいのでしょうか。
ファイルを分割すれば問題ないことではあるのですが、ひとつのファイルに収めたいため、質問させて頂きました。
以下にコードを示します。
C++
1#include<vector> 2#include<iostream> 3using namespace std; 4 5class Body; 6class Parent; 7class Child; 8 9class Parent 10{ 11public: 12 Parent(Body* body) : 13 mBody(body) 14 { 15 mBody->addParent(this); 16 } 17 18 void update() 19 { 20 updateParent(); 21 } 22 23 virtual void updateParent() 24 { 25 } 26 27private: 28 Body* mBody; 29}; 30 31class Child : public Parent 32{ 33public: 34 Child(Body* body) : 35 Parent(body) 36 { 37 } 38 39 virtual void updateParent() override 40 { 41 cout << "child" << endl; 42 } 43}; 44 45class Body 46{ 47public: 48 void initialize() 49 { 50 mChild = new Child(this); 51 } 52 53 void addParent(Parent* parent) 54 { 55 mParents.emplace_back(parent); 56 } 57 58 void runloop() 59 { 60 for(Parent* p : mParents){ 61 p->update(); 62 } 63 } 64 65private: 66 Child* mChild; 67 vector<Parent*> mParents; 68}; 69 70int main() 71{ 72 Body body; 73 body.initialize(); // オブジェクトの生成 74 body.runloop(); // メインループ 75 76 return 0; 77};
以下のエラーが出力されます。
test.cpp:15:8: error: invalid use of incomplete type ‘class Body’ mBody->addParent(this);
ParentクラスからaddParent()が見えないといっている模様です。
回答1件
あなたの回答
tips
プレビュー