C++类互访

结论:

     类需要先定义,而后才能被实例化,但是实际存在一种场景是:两个类需要相互引用或相互成为类中的子对象成员时,就无法先定义使用,在编译环节就出现错误导致编译失败,这时就需要用到前向声明,此外,前向声明的类不能被实例化。

   类的相互访问方式如下:

                                                                     

代码如下:

//CB类
//.h文件引用 CA头文件, .cpp无需引用 CA头文件,可访问 CA对象(.cpp 存在A的头文件)
//默认先调用 CB构造函数,再调用CA构造函数

-------------------------------.h文件----------------------------------
#include <iostream>
#include "B.h"

using namespace std;
class CA
{
private:
	int a;
public:
	CA();
	~CA();

	CB b;

	void setA(int a);

	int getA();

	void ShowBData();
};

------------------------------.cpp文件-----------------------------------

#include "stdafx.h"
#include "A.h"

CA::CA()
{
   cout << "CA Construct" << endl;
}

CA::~CA()
{
   cout << "CA Destroy" << endl;
}

void CA::setA(int a)
{
	this->a = a;
}

int CA::getA()
{
	return a;
}

void CA::ShowBData()
{
	cout << b.GetB() << endl;
}

 

//头文件 提前引入 class CA
//.cpp文件 加入CA的头文件
//CB中不能出现CA的对象,可以是指针,或者引用

--------------------------------------------.h文件-----------------------------------
#pragma once
#include<iostream>
using namespace std;

class CA;
class CB
{
private:
	int b;
public:
	CB();
	~CB();

	CA *a;

	int GetB();

	void SetB(int b);

	void ShowAData();
};


---------------------------------------.cpp文件-------------------------------

#include "stdafx.h"
#include "B.h"
#include "A.h"


CB::CB()
{
	cout << "CB Construct" << endl;
}


CB::~CB()
{
	cout << "CB Destroy" << endl;
}

int CB::GetB()
{
	return b;
}

void  CB::SetB(int b)
{
	this->b = b;
}

void  CB::ShowAData()
{
	cout << a->getA() << endl;
}

 

//定义CA,CB对象,并给变量赋值
#include "stdafx.h"
#include <iostream>
#include "A.h"
#include "B.h"
using namespace std;

int main()
{
	CA a;
	CB b;
	a.setA(1);
	b.SetB(2);

	a.b = b;
	b.a = &a; 

	a.ShowBData();
	b.ShowAData();

	while (1)
	{

	}
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值