[C++ 核心编程]笔记 4.4.1 全局函数做友元

4.4 友元

概述:

生活中你的家有客厅(Public),有你的卧室(Private)

客厅所有来的客人都可以进去,但是你的卧室是私有的,也就是说只有你能进去, 但是呢,你也可以允许你的好闺蜜好基友进去。

  • 在程序里,有些私有属性 也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术
  • 友元的目的就是让一个函数或者类 访问另一个类中私有成员
  • 友元的关键字为 friend

友元的三种实现

  1. 全局函数做友元
  2. 类做友元
  3. 成员函数做友元

4.4.1 全局函数做友元

cpp 复制代码
#include<iostream>
using namespace std;
#include<string>

//建筑物类
class Building
{
	//goodGay全局函数是 Building的好朋友, 可以访问Building中私有成员
	friend void goodGay(Building* building);

public:
	Building()
	{
		m_SittingRoom = "客厅";
		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 test01()
{
	Building building;
	goodGay(&building);
}
int main()
{
	test01();


	system("pause");
	return 0;
}```
相关推荐
凉、介4 小时前
Armv8-A virtualization 笔记 (二)
笔记·学习·嵌入式·arm·gic
YL200404264 小时前
048路径总和III
数据结构·dfs
z200509304 小时前
每日简单算法题——————跟着卡尔
算法
智者知已应修善业5 小时前
【ICL8038芯片正弦波三角波方波发生器电路】2024-1-5
驱动开发·经验分享·笔记·硬件架构·硬件工程
踩着两条虫5 小时前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
JoneBB5 小时前
ABAP Webservice连接
运维·开发语言·数据库·学习
探序基因5 小时前
身高与基因的关系
笔记
即使再小的船也能远航5 小时前
【Python】安装
开发语言·python
Irissgwe5 小时前
类与对象(三)
开发语言·c++·类和对象·友元
️是785 小时前
信息奥赛一本通—编程启蒙(3395:练68.3 车牌问题)
数据结构·c++·算法