我正在尝试编译如下内容:


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

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


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

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

到目前为止,使用前向声明还没有问题,但是现在可以使用它,因为我不能使用仅向前声明的类的属性或方法。

我该如何解决?

最佳答案

只要我正确理解您的问题,您需要做的就是:


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

丙型肝炎
#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() {}


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

丙型肝炎
#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() {}

关于c++ - 循环依赖C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13405906/

10-11 15:25