2

私は次のようなものをコンパイルしようとしています:

ああ

#include "B.h"
class A {
    B * b;
    void oneMethod();
    void otherMethod();
};

A.cpp

#include "A.h"
void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}

Bh

#include "A.h"
class B {
    A * a;
    void oneMethod();
    void otherMethod();
};

B.cpp

#include "B.h"       
void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}

これまで、前方宣言の使用に問題はありませんでしたが、前方宣言されたクラスのみの属性やメソッドを使用できないため、今はそれを使用できます。

どうすればこれを解決できますか?

4

4 に答える 4

6

C ++では、JavaやC#とは異なり、クラスの外部でメンバー関数(その本体を提供する)を定義できます。

class A;
class B;

class A {
    B * b;
    void oneMethod();
    void otherMethod() {}
};

class B {
    A * a;
    void oneMethod();
    void otherMethod() {}
};

inline void A::oneMethod() { b->otherMethod(); }
inline void B::oneMethod() { a->otherMethod(); }
于 2012-11-15T20:49:10.390 に答える
2

私があなたの質問を正しく理解している限り、あなたがする必要があるのはこれだけです:

ああ

class B;// Forward declaration, the header only needs to know that B exists
class A {
    B * b;
    void oneMethod();
    void otherMethod();
};

A.cpp

#include "A.h"
#include "B.h"//Include in the .cpp since it is only compiled once, thus avoiding circular dependency
void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}

Bh

class A;// Forward declaration, the header only needs to know that A exists
class B {
    A * a;
    void oneMethod();
    void otherMethod();
};

B.cpp

#include "B.h" 
#include "A.h"//Include in the .cpp since it is only compiled once, thus avoiding circular dependency      
void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}
于 2012-11-15T20:58:58.677 に答える
1

クラスが定義されるまで、クラスのメンバーの使用を延期する必要があります。あなたの場合、それはいくつかのメンバー関数本体をファイルの一番下に移動することを意味します:

class B;

class A {
    B * b;
    void oneMethod();
    void otherMethod() {}
};

class B {
    A * a;
    void oneMethod() { a->otherMethod() }
    void otherMethod() {}
};

inline void A::oneMethod() { b->otherMethod() }

複数のファイルでの一般的な解決策は次のとおりです。

ああ

class B;
class A {
    B * b;
    void oneMethod();
    void otherMethod();
};

Bh

class A;
class B {
    A * a;
    void oneMethod();
    void otherMethod();
};

A.cpp

#include "A.h"
#include "B.h"

void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}

B.cpp

#include "A.h"
#include "B.h"

void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}

main.cpp

#include "A.h"
int main () { A a; a.oneMethod(); }
于 2012-11-15T20:50:06.230 に答える
0

関数の実装をcppファイルにプッシュすると、cppに両方のヘッダーを含めることができます。

于 2012-11-15T20:49:18.837 に答える