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 复制代码
好基友正在访问客厅
好基友正在访问卧室
相关推荐
端平入洛20 小时前
delete又未完全delete
c++
端平入洛2 天前
auto有时不auto
c++
郑州光合科技余经理3 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1233 天前
matlab画图工具
开发语言·matlab
dustcell.3 天前
haproxy七层代理
java·开发语言·前端
norlan_jame3 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20213 天前
信号量和信号
linux·c++
多恩Stone3 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054963 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月3 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js