【发布时间】:2023-02-21 09:48:44
【问题描述】:
我有两个类,A 和B,它们相互依赖:
class A {
public:
B* b;
A() {
b = new B();
}
};
class B {
public:
A* a;
B() = default;
};
这段代码将无法编译,因为存在循环依赖链。但是,即使我转发声明类 B 来解决循环依赖,仍然存在错误:
.code.tio.cpp:7:11: error: allocation of incomplete type 'B'
b = new B();
^
我相信这个错误表明我无法初始化 B 因为它是一个前向声明的类,但我仍然需要 A 和 B 相互依赖,那么我该如何解决这个错误?
【问题讨论】:
标签: c++ circular-dependency forward-declaration