クラスの相互参照を解決できません。
AクラスとBクラスが互いにポインタを持ち合って、互いのメソッドを呼び合うようにしたいのですが、コンパイルが通りません。
以下にコードを掲載します。
C++
1// a.h 2#ifndef A_H 3#define A_H 4 5#include <iostream> 6#include "b.h" 7using namespace std; 8 9class A { 10public: 11 void aPrint(); 12 B *b; 13}; 14 15#endif
C++
1// a.cpp 2#include "a.h" 3 4void A::aPrint() { 5 cout << "A" << endl; 6 b->bPrint(); 7}
C++
1// b.h 2#ifndef B_H 3#define B_H 4 5#include <iostream> 6#include "a.h" 7using namespace std; 8 9class B { 10public: 11 void bPrint(); 12 A *a; 13}; 14 15#endif
C++
1// b.cpp 2#include "b.h" 3 4void B::bPrint() { 5 cout << "B" << endl; 6 a->aPrint(); 7}
C++
1// main.cpp 2#include <iostream> 3#include "a.h" 4#include "b.h" 5using namespace std; 6 7int main() { 8 A a; 9 B b; 10 11 a.b = &b; 12 b.a = &a; 13 14 a.aPrint(); 15 b.bPrint(); 16 17 return 0; 18}
インターネットで調べたところ、AクラスのヘッダにBクラスの前方宣言を書いて、BクラスのヘッダにAクラスの前方宣言を書けば解決できるようなことが書いてあったのですが、コンパイルは通りませんでした。
どのように修正すれば、コンパイルが通るようになりますでしょうか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/08 06:15