C++中两个类互相引用的解决

A的头文件A.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef _A
#define _A
#include "B.h"

class A
{
private :
int a;
B objectb; //A的头文件导入了B的头文件,在调用B的时候就可以不用指针
public :
A();
int geta();
void handle();
};
#endif _A


B的头文件B.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef _B
#define _B

extern class A; //注意1:需要用extern声明A
class B
{
private :
int b;
A* objecta; //注意2:调用A的时候需要用指针
public :
B();
int getb();
void handle();
};
#endif _B


A的定义文件A.cpp:


#include <iostream>
#include "A.h"
using namespace std;
A::A()
{
this ->a= 100 ;
}
int A::geta()
{
return a;
}
void A::handle()
{
cout<< "in A , objectb.b=" <<objectb.getb()<<endl; pre= "" <= "" }= "" ><br>
}

B的定义文件B.cpp:
#include <iostream>
<strong>#include "B.h"
#include "A.h" //注意3:在B.cpp里面导入A的头文件
using namespace std;
B::B()
{
this ->b= 200 ;
}
int B::getb()
{
return b;
}
void B::handle()
{
}

#include <iostream>
#include <cstdlib>
using namespace std;
void main()
{
A a;
a.handle();
B b;
b.handle();
system( "pause" );
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值