如果两个类必须相互包含,我应该如何排列它们的头文件并避免不完整的类型

How should I arrange header files of two classes and avoid incomplete type if they have to include each other?

本文关键字:文件 排列 类型 两个 我应该 如果 包含 何排列      更新时间:2023-10-16

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,你不应该担心它,但如果你不担心,如果你不知道如何使用,你需要在你的工具链中查找它。