C++头文件相互#include时做如下处理:
- 在"testa.h"中 #include "testb.h".
- 在"testb.h"中用类的前置声明: class testA;
- 宏定义处理( #ifndef *** #define *** #endif)
示例如下:
(1)"testa.h":
#ifndef HEADER_TESTA
#define HEADER_TESTA
#include "testb.h"
class testA
{
testB* pB;
testB b;//正确,因为此处已经知道CB类的大小,且定义了CB,可以为b分配空间
};
#endif //HEADER_TESTA
(2)"testb.h":
#ifndef HEADER_TESTB
#define HEADER_TESTB
class testA;
//这个必须要用,不能只用#include "testa.h",如果只是#include "testa.h"而没有class testA;则会报错.
class testB
{
testA* pA;
//testA a;//错误,因为此时还不知道CA的大小,无法分配空间
};
#endif //HEADER_TESTB
(3)"testA.cpp":
#include "testa.h"
但是.cpp文件只能#include “testa.h”.如果#icnlude “testb.h”则错误(展开后testA不识别testB).
testB.h重复包含
定义了两个头文件
//a.h
#include"b.h"
class a
{
…
b *b1;
};
//=========================
//b.h
#include "a.h"
class b
{
…
a *a1;
};
编译报错了。
解决方式如下:
解决方法一:(亲测可用)
//a.h
class b; //由原来的#include "b.h"变为class b;(或者相反)
class a
{
…
b *b1;
};
//=========================
//b.h
#include "a.h"
class b
{
…
a *a1;
};
不需要这么包含,除非必要,如果你只是想在另外一个类中定义一个类的成员变量,只要在头文件中加入 class 类名;然后要在.cpp文件中再包含这个头文件就可以了。因为这种方式只是在头文件中包含了该类,在源文件中还不包含,这样做只是为了避免相互包含报错。
解决方法二:
加入宏定义
a.h
#ifndef __A_H__
#define __A_H__
class b;
class a
{
...
}
#endif
b.h
#ifndef __B_H__
#define __B_H__
class a;
class b
{
...
}
#endif