黑马程序员c++ 友元

全局函数做友元

作用:使类外函数或类访问类内私有属性

方法:在类内加友元函数声明:friend void func();

#include <iostream>
#include <string>

using namespace std;

class Building
{
	friend void text();	//将访问私有成员的全局函数设为友元,全局函数就能访问私有成员 
public:
	
	string m_settingroom;
	
	Building()
	{
		m_settingroom = "客厅";
		m_bedroom = "卧室";
	}
	
private:
	
	string m_bedroom;
};

void text()
{
	Building building;
	
	cout << "正在访问" << building.m_settingroom << endl;
	cout << "正在访问" << building.m_bedroom << endl;	//m_bedroom作为私有成员不能在类外被普通全局函数访问 
}

int main()
{
	text();
	
	return 0;
}

类做友元

作用:另一个类可以访问类的私有属性

方法:friend class Person;

#include <iostream>
#include <string>

using namespace std;

class GoodGay1
{
public:
	
	Building *m_building;
	
	GoodGay1();
	void visit();
};

class Building
{
	friend class GoodGay1;	//将访问私有成员的类设为友元,类就能访问私有成员 
	
public:
	
	string m_settingroom;
	
	Building()
	{
		m_settingroom = "客厅";
		m_bedroom = "卧室";
	}
	
private:
	
	string m_bedroom;
};

GoodGay1::GoodGay1()
{
	m_building = new Building;
}
//在函数名之前声明作用域 
void GoodGay1::visit()
{
	cout << "正在访问" << m_building -> m_settingroom << endl;
	cout << "正在访问" << m_building -> m_bedroom << endl;	//m_bedroom作为私有成员不能在类外被普通类访问 
}

void text()
{
	GoodGay1 goodgay1;
	goodgay1.visit();
}

int main()
{
	text();
	
	return 0;
}

成员函数做友元

作用:使成员函数可以访问类中的私有属性

方法:friend void Person:: func(){};

#include <iostream>
#include <string>

using namespace std;

class Building;

class GoodGay2
{
public:
	
	Building *m_building;
	
	GoodGay2();
	void visit1();
	void visit2();
};

class Building
{
	friend void GoodGay2::visit2(void);	//将另一个类的成员函数设为友元,成员函数才能访问私有成员 
	
public:
	
	string m_settingroom;
	
	Building()
	{
		m_settingroom = "客厅";
		m_bedroom = "卧室";
	}
	
private:
	
	string m_bedroom;
};

GoodGay2::GoodGay2()
{
	m_building = new Building;
}
//在函数名之前声明作用域 
void GoodGay2::visit1()
{
	cout << "正在访问" << m_building -> m_settingroom << endl;
//	cout << "正在访问" << m_building -> m_bedroom << endl;	//不是友元的类中 成员函数不能访问另一个类中的私有成员 
}

void GoodGay2::visit2()
{
	cout << "正在访问" << m_building -> m_settingroom << endl;
	cout << "正在访问" << m_building -> m_bedroom << endl;	//不是友元的类中,将成员函数设置为友元才能访问另一个类中的私有成员 
}

void text()
{
	GoodGay2 goodgay2;
	goodgay2.visit1();
	goodgay2.visit2();
}

int main()
{
	text();
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值