循环包含在C++中
Circular includes in C++ - again
Main.cpp
#include "Test1.h"
#include "Test2.h"
int main(){
Test1 t1;
Test2 t2;
t1.process(t2);
t2.process(t1);
}
测试1.h
#ifndef TEST1
#define TEST1
#include "Test2.h"
class Test1 {
public:
void process(const Test2& t) {};
};
#endif // !TEST1
测试2.h
#ifndef TEST2
#define TEST2
#include "Test1.h"
class Test2 {
public:
void process(const Test1& t) {};
};
#endif // !TEST2
VS2012表示:
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2143: syntax error : missing ',' before '&'
error C2664: 'Test2::process' : cannot convert parameter 1 from 'Test1' to 'const int'
我很确定这是循环包含的问题(我偶尔会遇到它(,但这次我不确定为什么不编译。
注意:类只依赖于彼此的引用,这些引用的大小是已知的。是因为包含保护(#ifndef
(,使得其中一个测试头将另一个作为空文件包含吗?
如果您坚持这样做,您需要在每个.h文件中转发声明您的类,以便编译器知道它是什么。
#include "Test1.h"
class Test1;
class Test2 {
public:
void process(const Test1& t) {};
};
完全展开预处理器指令,您会看到问题:Main.cpp包含Test1.h,其中包含Test2.h,因此在定义Test1
之前,将首先编译class Test2
,从而导致missing type specifier
错误。您可能可以通过前向声明Test1
并说void process(const class Test1& t)
而不仅仅是void process(const Test1& t)
来解决此问题。
您需要在其中一个的头中放入另一个的前向声明。如果在Test2.h中转发声明Test1(在声明Test2之前(,则可以从Test2.h删除#include "Test1.h"
。
如果您在头中有一个指向类型的引用或指针,请尝试使用前向声明。
// Within stop Test2.h
class Test1;
在test1.h
和test2.h
中,可以分别使用Test2
和Test1
的前向声明来避免包含。只需将class Test1;
替换为#include "test1.h"
即可。
然后仅在实现文件中包含test1.h
。
请参阅此问题
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 编译包含字符串的代码时遇到问题
- c++库的公共头文件中应该包含什么
- 将包含C样式数组的对象初始化为成员变量(C++)
- 是否需要删除包含对象的"pair"?
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 使用mongocxx驱动程序时包含头文件问题
- 如何在h文件中包含.o对象文件
- 在混合代码库中将C转换为C++时出现许多包含错误
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- cmath抛出错误C2062、C2059、C2143和C2447.cmath包含在矢量文件中
- 为什么您需要C++头文件的包含保护
- 无法在UE4中包含BP类到CPP类
- g++ 说函数不存在,即使包含正确的标头
- 在C++代码中包含opencv时,使用ctypes创建.so文件
- Visual C++GC接口如何启用它以及要包含哪个库
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)