我有两个标题,A 和 B。它们看起来像这样:
// A.h
#include "B.h";
class A {
// stuff
AFunction(B* b);
OtherFunction();
}
// B.h
class A;
BFunction(A* a);
这是我第一次尝试解决循环依赖,所以我不太确定我在做什么。我的问题如下:BFunction 在某些时候调用 a->OtherFunction();
。我得到一个错误,因为 OtherFunction 没有前向声明,显然我也不能前向声明它。这种情况是对称的(AFunction 调用 b->SomeOtherFunction()),所以我无法通过交换 include 和 forward 声明来修复它。
我该如何解决?
最佳答案
如果您需要有关 A 或 B 的任何信息,而不仅仅是分配它们类型的指针,那么您必须将相关代码移动到 .cpp 文件中,因为您不能将它们包含在循环中方式。解决方法如下:
啊啊
class B; // forward declaration
class A {
B* b;
// legal, you don't need to know anything about B
void set(B* b) { this->b = b; }
// must be implemented in .cpp because it needs to know B
void doSomethingWithB();
};
A.cpp
#include "A.h"
#include "A.h"
void A::doSomethingWithB() {
b->whatever();
B.h
class A
class B {
void methodWithA(A* a);
};
B.cpp
#include "B.h"
#include "A.h"
void B::methodWithA(A* a) {
a->whatever();
}
关于c++ - 循环依赖和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14168737/