C++ 两个类互相调用

总所周知,我们想要调用一个类,一定要添加他的头文件。例如,class A 调用class B,
在class A 头文件中,这样子就可以了。如:
A.h

#ifndef A_H
#define A_H
#include "B.h"
class A
{
public:
    A();
    B b;
};

#endif

但是,如果我想class A 调用class B , class B 调用class A呢,如果使用A的头文件包含B的头文件,B的头文件包含A的头文件,这样是否可行?
a.h

#ifndef A_H
#define A_H
#include "b.h"
class A
{
public:
    A();
    B b;
};
#endif // A_H

b.h

#ifndef B_H
#define B_H
#include "a.h"
class B
{
public:
    B();
    A a;
};
#endif // B_H

编译出错

b.h:8: error: 'A' does not name a type

所以,这样不行的。

---------------------下面才是正确的办法----------------------------------
直接上代码:
a.h

#ifndef A_H
#define A_H
class B;
class A
{
public:
    A();
    B *b;
};
#endif // A_H

a.cpp

#include "a.h"
#include "b.h"
A::A()
{
}

为什么在a.cpp中include b.h,因为需要调用b的接口。

b.h

#ifndef B_H
#define B_H
#include "a.h"
class B
{
public:
    B();
    A a;
};
#endif // B_H

还有一种办法,在A,B类头文件中相互引用头文件,将A或者B设计为单例模式。

  • 8
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值