- 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
{
B b;
}
class B
{
A* 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
{
B b;
}
class B
{
A a;
}
- When the compiler declares a, a compilation error occurs because the declaration of B is below a
- Then, in the definition because the mutual reference will certainly need to include the header file, if only in the respective header file contains the other side of the header file, is not compiled, as follows:
//class A.h
#include "B.h"
class A
{
B b;
}
//class B.h
#include "A.h"
class B
{
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
{
B b;
}
//class B.h
class A;
class B
{
A *a;
}
//B.cpp
//在B.cpp中的文件包含处要有下面语句,否则不能调用成员a的任何内容
#include "A.h"
B::B()
{
……
}
Moreover, in B.h, because it is a class A, the way to declare, you can only define a pointer or reference in class B's declaration.
From for notes (Wiz)
C + + Two classes that contain references to one another