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 复制代码
好基友正在访问客厅
好基友正在访问卧室
相关推荐
百锦再21 小时前
python之路并不一马平川:带你踩坑Pandas
开发语言·python·pandas·pip·requests·tools·mircro
灏瀚星空21 小时前
基于 Python 与 GitHub,打造个人专属本地化思维导图工具全流程方案(上)
开发语言·人工智能·经验分享·笔记·python·个人开发·visual studio
是Dream呀21 小时前
Python从0到100(一百):基于Transformer的时序数据建模与实现详解
开发语言·python·transformer
我是一只小青蛙88821 小时前
Windows下MATLAB与C++混合编程实战
c++
草莓熊Lotso21 小时前
Python 入门超详细指南:环境搭建 + 核心优势 + 应用场景(零基础友好)
运维·开发语言·人工智能·python·深度学习·学习·pycharm
*TQK*21 小时前
Python中as 的作用
开发语言·python
维他奶糖6121 小时前
Python 实战:Boss 直聘职位信息爬虫开发全解析
开发语言·爬虫·python
颜颜yan_21 小时前
Python中秋月圆夜:手把手实现月相可视化,用代码赏千里共婵娟
开发语言·python·可视化·中秋节
xwill*21 小时前
python 格式化输出详解(占位符:%、format、f表达式
开发语言·pytorch·python·深度学习
yingjuxia.com21 小时前
【python】错误SyntaxError: invalid syntax的解决方法总结
开发语言·python