如何在 C++ 中初始化前向声明的类 [重复]

问题描述 投票:0回答:1

我有两个班级,

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
1个回答
2
投票

为了解决这个问题,将

A()
构造函数的主体移动到定义完整
B
类之后的某个地方,如下所示:

class B;

class A {
public:
    B* b;
    A();
};

class B {
public:
    A* a;
    B() = default;
};

A :: A() {
   b = new B();
}
© www.soinside.com 2019 - 2024. All rights reserved.