【c++】 在一个头文件中引用另一个头文件的类

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谁吃薄荷糖

你获得知识,我获得财富,双赢!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值