成员函数做友元——类和对象

在c++中,友元有三种实现方式:全局函数做友元;类做友元;成员函数做友元;

前面两篇介绍了全局函数做友元;类做友元;下面介绍成员函数做友元示例;

#include<iostream>
#include<string>
///成员函数做友元,成员函数必须写在类外定义,在类内定义会报错
using namespace std;
class Building;//先声明这个类,稍后GoodGay会用到,避免编译器报错
class GoodGay
{
public:
	GoodGay();//默认构造函数
	void Visit();//让Visit成为Building的好朋友,可以访问的私有属性
	void  Visit2();让Visit2()不可以访问的私有属性
	Building* building;
};
class Building
{
	friend void GoodGay::Visit();//让Visit成为Building的好朋友,可以访问的私有属性
	//friend void GoodGay::Visit2();
public:
	Building();
public:
	string m_SittingRoom;
private:
	string m_BedRoom;
};

Building::Building()
{
	m_SittingRoom = "客厅";
	m_BedRoom = "卧室";
}
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;
	//cout << "你的好基友正在访问" << building->m_BedRoom << endl;//这个没有声明友元函数,所以就不能访问私有属性
}
void test01()
{
	GoodGay gg;//创建一个对象
	gg.Visit();//通过对象访问函数
	gg.Visit2();//通过对象访问函数
}
int main()
{
	test01();
    system("puase");
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值