这个问题在这里已有答案:
我在两个不同的文件中定义了以下两个类:
#include "B.h"
class A {
public:
A() {}
~A() {}
f() {
auto b = new B(this);
}
};
在另一个文件中:
#include "A.h"
class B {
public:
B(A* a) {}
~B() {}
}
但我不明白我得到的编译错误:
B.h: error: ‘A’ has not been declared
A.cpp: error: no matching function for call to ‘B(A&)‘
*this);
note: candidate is:
note: B(int*)
note: no known conversion for argument 1 from ‘A’ to ‘int*’
为什么我的A类已经转换为int?
这是一个循环依赖问题。 qazxsw poi包括B.h
,而qazxsw poi包括A.h
。
实际上,你不需要在A.h
中使用B.h
,#include "A.h"
在这里不需要是B.h
(即在函数声明中使用它作为参数类型),A
就足够了。
complete type
你有一个循环依赖。 forward declaration的定义不能取决于class A; // forward declaration
class B {
public:
B(A* a) {}
~B() {}
};
的定义,如果后者取决于前者的定义。你可以通过将其中一个class A
指令转换为前向声明来解决这个问题。在你的情况下,
class B
尽管如此,您可能还需要在实现文件中定义#include
。但这很好,你可以在翻译单元中使用// Don't include the complete definition
// #include "A.h"
class A; // Instead: forward-declare A
class B {
public:
B(A* a) {}
~B() {}
};
,而不会回到循环依赖问题。