循环包括在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);
}
Test1.h p>
Test1.h
#ifndef TEST1
#define TEST1
#include "Test2.h"
class Test1 {
public:
void process(const Test2& t) {};
};
#endif // !TEST1
Test2.h
#ifndef TEST2
#define TEST2
#include "Test1.h"
class Test2 {
public:
void process(const Test1& t) {};
};
#endif // !TEST2
VS2012说:
VS2012 says:
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'
我确定它是再次(我偶尔遇到它),但这一次我不知道为什么不编译。
I am pretty sure it's the circular includes problem again (I come across it once in a while), but this time I am not sure why doesn't this compile.
注意:类只依赖于彼此的参考,其具有已知大小。是因为包含保护( #ifndef
),使一个Test头包括另一个作为一个空文件?
Notice: the classes only depend on each other's references, which are of known size. Is it because of the include guards (#ifndef
), that make one of the Test headers include the other as an empty file?
推荐答案
完全展开预处理器指令,你会看到问题:Main.cpp包括Test1.h,其中包括Test2.h,因此 class Test2
将被编译,在
Test1
之前定义,导致缺少类型说明符
错误。你可以通过向前声明 Test1
并说 void process(const class Test1& t)
void process(const Test1& t)
。
Fully expand the preprocessor directives and you'll see the problem: Main.cpp includes Test1.h which includes Test2.h, so class Test2
will be compiled first, before Test1
is ever defined, leading to the missing type specifier
error. You can probably fix this by forward-declaring Test1
and saying void process(const class Test1& t)
rather than just void process(const Test1& t)
.
这篇关于循环包括在C ++ - 再次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!