两个类之间相互引用问题
cpp在编译的时候需要知道类的大小,所以如果两个类相互引用会出现问题:
定义A的时候,A的里面有B,所以就需要去查看B的占空间大小,但是查看的时候又发现需要知道A的占空间大小,从而造成死循环。
方法一: 前置声明
前置声明适用的场景比较有限,如果类A中使用类B,B进行了前置声明:
- A中只能使用B的引用或指针,因为其内存大小空间是确定的。
- A中不能直接初始化指针。
- A中不能使用B中具体的成员。
由于只有B的前置声明,获取不到B的大小,不能直接声明对象。
class B;
class A {
// 1. B b;
//不能这样使用 会报错field ‘b’ has incomplete type
B *b;
public:
A(){
// 2. b = new B();
//不能这样使用 会报错field ‘b’ has incomplete type
// 3. b->f();
//不能这样使用 会报错field ‘b’ has incomplete type
};
}
方法一: 使用.h头文件
写两个头文件"a.h" “b.h”,里面存放类的成员声明,如果涉及引用类方法的调用,和对象的创建,另外写一个cpp文件。
“b.h”
#ifndef B_H
#define B_H
class A;// 优先使用前置声明 而不是include头文件
class B {
A *a;
public:
void f(){};
}
#endif
“a.h”
#ifndef A_H
#define A_H
#include “b.h"
class B {
B *b;
public:
void func();
}
#endif
“a.cpp”
#include "a.h"
A::A(){
b = new B();
}
void A::func(){
b->f(*this);
}
“main.cpp”
#include "a.cpp"
int main(){}