问题
Main.cpp
#include "Test1.h"
#include "Test2.h"
int main(){
Test1 t1;
Test2 t2;
t1.process(t2);
t2.process(t1);
}
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 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.
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?
回答1:
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)
.
回答2:
If you insist on doing this, you need to forward declare your class in each .h file so that the compiler knows what it is.
#include "Test1.h"
class Test1;
class Test2 {
public:
void process(const Test1& t) {};
};
回答3:
You will need to put a forward declaration of one of them in the header of the other. If you forward declare Test1 in Test2.h (before declaring Test2), you can remove #include "Test1.h"
from Test2.h.
回答4:
If you have a reference or pointer to a type within a header just try using a forward declaration.
// Within stop Test2.h
class Test1;
回答5:
In test1.h
and test2.h
you can use a forward declaration of Test2
and Test1
respectively avoiding the includes. Just put class Test1;
in place of #include "test1.h"
.
Then include test1.h
in the implementation file only.
See this question
来源:https://stackoverflow.com/questions/16404575/circular-includes-in-c-again