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 复制代码
好基友正在访问客厅
好基友正在访问卧室
相关推荐
倒头就睡的小比特19 小时前
算法竞赛C++常用的STL
c++·算法
weilx123420 小时前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!20 小时前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读21 小时前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
Smileyqp沛沛21 小时前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车21 小时前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光1 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
吞下星星的少年·-·1 天前
C++ 萌新语法入门篇
c++·算法比赛
霍霍的袁1 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
another heaven1 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法