C++中 两个类互为对方的成员类
说明
在设计时,有时会出现两个类互为对方的成员, 那么在编写头文件时,若两个类在两个文件中,那么可能会出现这样循环包含的问题。
为了解决循环包含的问题,这两个类首先要作为对方的指针的成员。
解决方法
-
两个头文件中使用前向说明
-
然后在类的具体实现中 分别引入两个头文件
A.h
// A.h
#ifndef A_H
#define A_H
// 前向声明 B 类
class B;
class A {
public:
A();
// 使用 B 类的指针
void doSomethingWithB(B* b);
private:
B* b_ptr;
};
#endif
B.h
// B.h
#ifndef B_H
#define B_H
// 前向声明 A 类
class A;
class B {
public:
B();
// 使用 A 类的指针
void doSomethingWithA(A* a);
private:
A* a_ptr;
};
#endif
A.cpp
// A.cpp
#include "A.h"
#include "B.h"
A::A() : b_ptr(nullptr) {}
void A::doSomethingWithB(B* b) {
b_ptr = b;
}
B.cpp
// B.cpp
#include "B.h"
#include "A.h"
B::B() : a_ptr(nullptr) {}
void B::doSomethingWithA(A* a) {
a_ptr = a;
}