[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;
}```
相关推荐
@大迁世界20 分钟前
告别 Go,拥抱 Rust
开发语言·golang·rust
SEO_juper21 分钟前
Node.js 重定向链检测工具:301 跳了几跳、有没有成环,一次看清
xml·开发语言·python·node.js·json·bash
学逆向的23 分钟前
C 指针常量与常量指针
c语言·开发语言·网络安全
Li_RuiQi39 分钟前
DAgger方法演进_独立学习笔记
笔记·学习·计算机视觉
小郎君6581 小时前
Vue keep-alive 切标签后滚动位置回顶?因为 onDeactivated 里读到的 scrollTop 是 0
算法
低调滴开发1 小时前
3 行代码写崩一个函数?切片才是 Rust 字符串处理的正确姿势
开发语言·后端·rust
CodeYp20191 小时前
第15讲:二叉搜索树
开发语言·c++·二叉搜索树
邵奈一1 小时前
GPT-6.1 Terra速度是Sol的3倍,价格减半
算法
RaaS1002 小时前
Node.js Brotli RCE 漏洞自查指南:fetch、undici、axios 都在影响面,三分钟确认你的版本
人工智能·深度学习·算法
猫猫.1532 小时前
HashTable、HashMap、ConcurrentHashMap 核心区别总结
java·开发语言·java-ee