循环依赖C ++

时间:2012-11-15 20:46:49

标签: c++ circular-dependency

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

A.H

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

A.cpp

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

B.h

#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 个答案:

答案 0 :(得分: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(); }

答案 1 :(得分:2)

只要我理解你的问题,你需要做的就是:

A.H

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() {}

B.h

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() {}

答案 2 :(得分: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() }

以下是多个文件中的典型解决方案:

A.H

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

B.h

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(); }

答案 3 :(得分:0)

将函数的实现推送到cpp文件中,然后cpp可以包含两个头文件。