包含头文件时出错
Error in including header file
嗨,我有两个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++中是不允许的)
相关文章:
- 读取文件的最后一行并输入到链接列表时出错
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 在 C/C++ 中打开驻留在 "/sys/" 下的文件时出错
- 在头文件中定义变量不会出错
- 如何在多写入器情况下对文件支持的共享内存中的大页面出错
- JNI,使用两个 .so 文件时出错,其中一个文件需要另一个文件
- 生成文件中隐式规则中的 -c 标志出错
- 编译时出错 - 链接.cpp和头文件
- 从人员矢量插入和读取文件时出错
- LNK2019 在文件中调用静态成员的方法时出错.cpp
- ./main:加载共享库时出错:libopencv_highgui.so.4.0:无法打开共享对象文件:没有这样的文件或
- 猫鼬 - 包含标准C++库文件时出错
- 在f2c.h文件中定义min()max()宏时出错
- ASIOSDK;从hostsample.cpp生成mex文件时出错
- 使用emscripten将c++文件转换为wasm时出错
- 将文本从一个文件复制到另一个c++流时出错
- 在C++目录中搜索文件的函数输出中出错
- 编译包含LLVM API标头的C++文件时出错
- MySQL C++连接器:添加符号时出错:文件格式无法识别