C++:友元

友元

(1)全局函数做友元

cpp 复制代码
class 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 test() {
	Building building;
	goodGay(&building);
}
int main() {
	test();
}

运行结果:

cpp 复制代码
全局函数 正在访问:客厅
全局函数 正在访问:卧室

(2)类做友元

cpp 复制代码
class Building {
	friend class GoodGay;
public:
	Building(); //构造函数
	string m_SittingRoom; //客厅

private:
	string m_BedRoom; //卧室
};

//类外写成员函数
Building::Building() {
	m_SittingRoom = "客厅";
	m_BedRoom = "卧室";
}

class GoodGay {
public:
	GoodGay();
	void visit(); //访问Building中的属性

	Building *building;

};

GoodGay::GoodGay() {
	//创建建筑物对象
	building = new Building;
}

void GoodGay::visit() {
	cout << "好基友正在访问" << building->m_SittingRoom << endl;
	cout << "好基友正在访问" << building->m_BedRoom << endl;
}

void test() {
	GoodGay gg;
	gg.visit();
}

int main() {
	test();
}

运行结果:

cpp 复制代码
好基友正在访问客厅
好基友正在访问卧室

(2)成员函数做友元

cpp 复制代码
class Building;

class GoodGay {
public:
	GoodGay(); //构造函数
	void visit1(); //访问Building中的属性
	void visit2();

private:
	Building *building;

};

class Building {
	friend void GoodGay::visit1();
public:
	Building(); //构造函数
	string m_SittingRoom; //客厅

private:
	string m_BedRoom; //卧室
};

//类外写成员函数
Building::Building() {
	m_SittingRoom = "客厅";
	m_BedRoom = "卧室";
}



GoodGay::GoodGay() {
	//创建建筑物对象
	building = new Building;
}

void GoodGay::visit1() {
	cout << "好基友正在访问" << building->m_SittingRoom << endl;
	cout << "好基友正在访问" << building->m_BedRoom << endl;
}

void GoodGay::visit2() {
	cout << "好基友正在访问" << building->m_SittingRoom << endl;
	//cout << "好基友正在访问" << building->m_BedRoom << endl;
}

void test() {
	GoodGay gg;
	gg.visit1();
}
int main() {
	test();
}

运行结果:

cpp 复制代码
好基友正在访问客厅
好基友正在访问卧室
相关推荐
j_xxx404_1 小时前
Linux:静态链接与动态链接深度解析
linux·运维·服务器·c++·人工智能
叶小鸡1 小时前
Java 篇-项目实战-苍穹外卖-笔记汇总
java·开发语言·笔记
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题】【Java基础篇】第22题:HashMap 和 HashSet 有哪些区别
java·开发语言·哈希算法·散列表·hash
c++之路2 小时前
C++23概述
java·c++·c++23
时空系2 小时前
第10篇:继承扩展——面向对象编程进阶 python中文编程
开发语言·python·ai编程
CHANG_THE_WORLD3 小时前
python 批量终止进程exe
开发语言·python
古城小栈3 小时前
从 cargo-whero 库中,找到提升 rust 的契机
开发语言·后端·rust
学涯乐码堂主3 小时前
有趣的“打擂台算法”
c++·算法·青少年编程·gesp
云栖梦泽4 小时前
Linux内核与驱动:14.SPI子系统
linux·运维·服务器·c++
Gary Studio4 小时前
安卓HAL C++基础-智能指针
开发语言·c++