Original: http://blog.csdn.net/leo115/article/details/7395077
When constructing your own class, it is possible to encounter mutual reference problems between the two classes, for example: a type defined in Class A class b,a is used and a type defined by a is used in B.
Class A
{
int i;
b b;
}
Class B
{
int i;
* A;
}
Note that the definition above, in general, can not appear Class A, class B mutual references are defined objects, that is, the following look:
Class A
{
int i;
b b;
}
Class B
{
int i;
A;
}
In this case, think of a a.b.a.b.a.b.a.b.a.b ..., a little bit of the descendants of the endless, then my machine can not bear. The main thing is that this kind of relationship is difficult to exist and difficult to manage. This definition is analogous to a dead loop in a program. So, in general, the definition of both, at least one side uses pointers, or both use pointers, but must not define entity objects.
To get to the end, then, in the definition of mutual references will definitely need to include header files, if only in their own header file contains the other side of the header file, is not compiled, as follows:
Class A.h
#include "B.h"
Class A
{
int i;
b b;
}
Class B.h
#include "A.h"
Class B
{
int i;
A *a;
}
The inclusion method above may cause the compiler to have an error message: The A.h file uses the type B.
What to do?
The general practice is: In the header file of two classes, select a header file containing another class, but the other header file can only be in the form of class *, and in the implementation file (*.cpp) contains the header file, as follows:
Class A.h
#include "B.h"
Class A
{
int i;
b b;
}
Class B.h
Class A;
Class B
{
int i;
A *a;
}
B.cpp
The file contained in B.cpp must have the following statement, or you cannot invoke any of the contents of member a
#include "A.h"
B::b ()
{
......
}
"Go" two classes in C + + have reference problems with one another