gpt4 book ai didi

C++ - 两个类相互实例化,不能使用前向声明

转载 作者:太空宇宙 更新时间:2023-11-03 10:32:18 26 4
gpt4 key购买 nike

我有 A 类和 B 类,它们的头文件都带有 include guards。一个是:

#ifndef A_H
#define A_H

#include "B.h"

class A
{
B b;
};

#endif

还有一个:

#ifndef B_H
#define B_H

#include "A.h"

class B
{
A a;
};

#endif

现在我用下面的 main.cpp 测试它:

#include "A.h"

int main()
{
A a;
}

编译错误如下:

# make main
g++ main.cpp -o main
B.h:8: error: ‘A’ does not name a type

除了使用指针/引用和前向声明之外,对于这种情况是否有任何解决方案?

最佳答案

不,这是不可能的:其中之一需要是指针或引用:因为如果 A 包含 B,B 又包含 A,A 又包含 B,那么您将进行无限递归,并试图指定无限大小的对象。

关于C++ - 两个类相互实例化,不能使用前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13365771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com