Jos*_* D. 2 c++ circular-dependency
我正在尝试编译以下内容:
啊
#include "B.h"
class A {
B * b;
void oneMethod();
void otherMethod();
};
Run Code Online (Sandbox Code Playgroud)
A.cpp
#include "A.h"
void A::oneMethod() { b->otherMethod() }
void A::otherMethod() {}
Run Code Online (Sandbox Code Playgroud)
BH
#include "A.h"
class B {
A * a;
void oneMethod();
void otherMethod();
};
Run Code Online (Sandbox Code Playgroud)
B.cpp
#include "B.h"
void B::oneMethod() { a->otherMethod() }
void B::otherMethod() {}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我没有遇到使用前向声明的问题,但我现在可以使用它,因为我不能使用只有前向声明的类的atributtes或方法.
我怎么解决这个问题?
在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(); }
Run Code Online (Sandbox Code Playgroud)