我知道这件事没有引起足够的重视,因为它很少见,但我想澄清一下。
说我有3个文件:
啊
#ifndef A_h
#define A_h
#include "B.h"
class A {
A();
virtual ~A();
bool someFunc(B& b);
};
#endif
h
#ifndef B_h
#define B_h
#include "A.h"
class B {
B();
virtual ~B();
bool someFunc(A& a);
};
#endif
和main.cpp
#include "A.h"
#include "B.h"
int main() { return 0; }
没有保护(#ifndef X_h #define X_h),则存在循环依赖性。添加保护应该可以解决问题,但是在第一次编译代码时,main.cpp会尝试包含a.h,而a.h会在声明a之前包含b.h并返回错误。如果我们将代码更改为:
啊
#ifndef A_h
#define A_h
class A {
A();
virtual ~A();
#include "B.h"
bool someFunc(B& b);
};
#endif
h
#ifndef B_h
#define B_h
class B {
B();
virtual ~B();
#include "A.h"
bool someFunc(A& a);
};
#endif
现在已经解决了循环依赖性,但是代码编译没有错误,但是Eclipse仍然返回错误:A.h中的“无法解析类型'B'”,因此您需要在使用了另一个的A.h和B.h中都添加surpress。我想知道是否存在另一种方法来解决循环依赖性而又不会导致Eclipse返回错误,以及如果我们有两个以上的类(A包括B,C和D; B包括A,C,D等),代码应该如何显示。 )
最佳答案
只要您实际上并没有在类B
中使用类A
的实例,而是仅声明带有指针或引用的函数,就可以完全不包含任何内容,而只声明类:
在文件A.h中
#ifndef A_h
#define A_h
class B; // Declare class B
class A {
A();
virtual ~A();
bool someFunc(B& b);
};
#endif
在B.h
#ifndef B_h
#define B_h
class A; //Declare class A
class B {
B();
virtual ~B();
bool someFunc(A& a);
};
#endif
当然,在定义(实现)功能的源文件中,您需要同时包含两个文件。