包含头文件时出错

Error in including header file

本文关键字:出错 文件 包含头      更新时间:2023-10-16

嗨,我有两个A类和B类。在 A 中,我正在使用 B 的头文件,以便我可以为 B(例如 B *b)创建一个实例,我在 B 类中正在做的事情也包括 A 的头文件并在 B 中创建 A 的实例(例如 A * a)。

当我在 B 中包含 A 的头文件时,它在 A.h 中给了我以下错误

1>c:BibekA.h(150) : error C2143: syntax error : missing ';' before '*'
1>c:BibekA.h(150)(150) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:BibekA.h(150)(150) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

听起来您正在以循环方式包含头文件(A.h 包括 B.h,其中包括 A.h)。 使用标头保护意味着当 B.h 在上述场景中包含 A.h 时,它会跳过它(由于现在 A.h 的包含保护处于活动状态),因此在解析 B.h 时尚未定义 A.h 中的类型。

若要解决此问题,可以使用前向声明:

// A.h
#ifndef A_H
#define A_H
// no #include "B.h"
class B; // forward declaration of B
class A {
  B* b;
};
#endif

B.H 也是如此

这允许您使用前向声明类的指针(例如,在成员变量的声明中,成员函数声明中),但不能在标头中以任何其他方式使用它。

然后在 A.cpp 中,您需要对 B.h 有正确的定义,因此您可以包含它:

// A.cpp
#include "A.h"
#include "B.h" // get the proper definition of B
// external definitions of A's member functions

此构造避免了头文件的循环包含,同时允许充分利用类型(在.cpp文件中)。

注意:关于不支持默认 int 的错误发生是因为编译器在包含 B.h 时没有正确的A定义(C 语言允许对未知类型进行默认int定义,但这在C++中是不允许的)