如果两个类必须相互包含,我应该如何排列它们的头文件并避免不完整的类型
How should I arrange header files of two classes and avoid incomplete type if they have to include each other?
A.h
#ifndef A_H_
#define A_H_
class A;
#include "B.h"
class A{
public :
A(const B &b) : bitem(b.data) {}
A() {}
private:
int bitem = 0;
};
#endif
B.h
#ifndef B_H_
#define B_H_
#include "A.h"
class B{
friend class A;
public:
B() {}
A func(){
A aitem;
return aitem;
}
private:
int data = 0;
};
#endif
main.cpp
#include "A.h"
#include "B.h"
int main()
{
return 0;
}
当我编译它时,我得到错误:
错误:返回类型"A类"不完整
但是如果我删除A.h中A类的前向声明,我会得到这样的错误:
错误:"A"未命名类型
我如何安排A和B?有什么循环定义吗?
在A.h 中转发声明B
class B;
删除include#include"B.h"
从标头中删除构造函数的定义,并将其移动到A.cpp中。在cpp中添加B.h的include。
当然你也必须把主模块和A模块连在一起。如果你正在使用IDE,你不应该担心它,但如果你不担心,如果你不知道如何使用,你需要在你的工具链中查找它。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 如何从 C 文件将引脚排列与 esp8266 一起使用?
- 问题 - 递归函数以返回文本文件排列
- 按线排列,通过轻重解析器解析巨大的XML文件
- 已知格式化文件中的数据排列
- 检查文本文件是否按字母顺序排列
- 如果两个类必须相互包含,我应该如何排列它们的头文件并避免不完整的类型
- 在c++中排列头文件
- 列出Unix目录中按大小排列的前10个文件