[C++核心编程](六):类和对象——友元(friend)

本文详细介绍了如何在C++中使用全局函数、类和类的成员函数作为友元,以便访问其他类的私有成员。通过实例展示了三种不同的友元应用场景。
摘要由CSDN通过智能技术生成

目的:让一个函数或者类访问另一个类中的私有成员

全局函数做友元

#include <iostream>
#include <string>

using namespace std;

class Building
{
	friend void GoodGay(Building& build); //全局函数作为友元,可以访问私有成员
private:
	string m_Bedroom;
public:
	string m_sittingroom;

	Building()
	{
		m_Bedroom = "卧室";
		m_sittingroom = "客厅";
	}
};

void GoodGay(Building& build)
{
	cout << "好基友正在访问:" << build.m_sittingroom << endl;
	cout << "好基友正在访问:" << build.m_Bedroom << endl;

}

void test()
{
	Building build;
	GoodGay(build);
}

int main(void)
{
	test();
	system("pause");
	return 0;
}

类做友元

#include <iostream>
#include <string>

using namespace std;

class Building
{     
	friend class GoodGay;//类做友元,GoodGay可以访问本类的私有属性
private:
	string m_Bedroom;
public:
	string m_sittingroom;

	Building();
};

Building::Building()
{
	m_Bedroom = "卧室";
	m_sittingroom = "客厅";
}

class GoodGay
{
public:
	void visit(); //访问building中的所有属性

	Building* building;

	GoodGay();
};

GoodGay::GoodGay()
{
	building = new Building;
}

void GoodGay::visit()
{
	cout << "好基友正在访问:" << building->m_sittingroom << endl;
	cout << "好基友正在访问:" << building->m_Bedroom << endl;
}

void test()
{
	GoodGay gg;
	gg.visit();
}

int main(void)
{
	test();
	system("pause");
	return 0;
}

类中的成员函数做友元

#include <iostream>
#include <string>

using namespace std;

class Building;
class GoodGay
{
public:
	void visit(); //访问building中的私有成员
	void visit2();//不可以访问building中的私有成员

	Building* building;

	GoodGay();
};

class Building
{     
	friend void GoodGay::visit(); //GoodGay下的visit可以访问本类的私有成员
private:
	string m_Bedroom;
public:
	string m_sittingroom;

	Building();
};

Building::Building()
{
	m_Bedroom = "卧室";
	m_sittingroom = "客厅";
}


GoodGay::GoodGay()
{
	building = new Building;
}

void GoodGay::visit()
{
	cout << "好基友正在访问:" << building->m_sittingroom << endl;
	cout << "好基友正在访问:" << building->m_Bedroom << endl;
}

void GoodGay::visit2()
{
	cout << "好基友正在访问:" << building->m_sittingroom << endl;
}

void test()
{
	GoodGay gg;
	gg.visit();
	gg.visit2();
}

int main(void)
{
	test();
	system("pause");
	return 0;
}

推荐文章:[C++核心编程](四):类和对象——对象特性

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值