C++学习笔记之友元

C++学习笔记之友元
  友元的目的就是让一个函数或者类访问另一个类中的私有成员。
 友元的关键字为friend
友元的三种实现

  • 全局函数做友元
#include <iostream>
#include <string>
using namespace std;


//全局函数做友元
class Building {
	//告诉编译器 goodgay全局函数 是 Building类的好朋友, 可以访问类中的私有内容
	friend void goodGay(Building* building);
public:
	Building() {
		this->m_SittingRoom = "客厅";
		this->m_BedRoom = "卧室";

	}
public:
	string m_SittingRoom;	//客厅
private:
	string m_BedRoom;		//卧室
};

void goodGay(Building* building) {
	cout << "好基友正在访问: " << building->m_SittingRoom << endl;
	cout << "好基友正在访问: " << building->m_BedRoom << endl;

}
void test00() {
	Building b;
	goodGay(&b);
}
int main() {
	test00();
	return 0;
}
  • 类做友元
#include <iostream>
#include <string>
using namespace std;
class Building {
	//告诉编译器 goodGay类是Building类的好朋友,可以访问到Building类中私有成员
	friend class goodGay;
public:
	Building();
public:
	string m_SittingRoom;	//客厅
private:
	string m_BedRoom;	//卧室
};

class goodGay {
public:
	goodGay();
	void visit();
private:
	Building* building;
};

Building::Building()
{
	this->m_SittingRoom = "客厅";
	this->m_BedRoom = "卧室";
}

goodGay::goodGay() {
	building = new Building;
}
void goodGay::visit() {
	cout << "好基友正在访问: " << building->m_SittingRoom << endl;
	cout << "好基友正在访问: " << building->m_BedRoom << endl;
}
void test00() {
	goodGay guy;
	guy.visit();
}
int main() {
	test00();
	return 0;
}
  • 成员函数做友元
#include <iostream>
#include <string>
using namespace std;

class Building;
class goodGay {
public:
	goodGay();
	void visit();
private:
	Building* building;
};
class Building {
	friend void goodGay::visit();
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 test00() {
	goodGay gg;
	gg.visit();
}
int main() {
	test00();
	return 0;
}

答案:
C++学习笔记之友元

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值