[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;
}```
相关推荐
EmmaXLZHONG13 小时前
Django By Example - 学习笔记
笔记·python·学习·django
不写八个13 小时前
PHP教程005:配置ThinkPHP环境
开发语言·php
迷海13 小时前
C++内存对齐
开发语言·c++
cxr82813 小时前
细胞球运动追踪的卡尔曼滤波与力场插值算法 —— 活体内微米级颗粒实时定位与轨迹预测系统
算法
炘爚13 小时前
C++(流类:istream /ostream/istringstream /ostringstream)
开发语言·c++·算法
Gse0a362g13 小时前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
android·开发语言·php
!停13 小时前
C++入门—内存管理
java·jvm·c++
A.A呐13 小时前
【C++第二十五章】智能指针
c++
倒酒小生13 小时前
日拱一卒,滴水穿石
数据结构