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 复制代码
好基友正在访问客厅
好基友正在访问卧室
相关推荐
恋恋西风2 小时前
C++ 理解 std::thread 在单核和多核上的行为差异
开发语言·c++
Brilliantwxx2 小时前
【Linux】 进程(9)程序与进程地址空间(基础+进阶+面试题)
linux·运维·服务器·开发语言·c++
BizzZ_3 小时前
C++(22)——类型转换和IO流
开发语言·c++
小范同学_3 小时前
JDK1.7 与 JDK1.8 HashMap 底层原理对比 + 数组并发扩容死循环详解
java·开发语言
geovindu3 小时前
CSharp: 万年历
开发语言·后端·c#·.net
我找到地球的支点啦4 小时前
Matlab系列(009) 一CRC循环冗余校验详解
开发语言·数据结构·算法·matlab·信息与通信
予昊4 小时前
从零实现“在线五子棋对战“:WebSocket 实时通信 + 段位匹配
java·开发语言·网络·websocket
weixin_461408584 小时前
Mybatis-flex小记
java·开发语言·mybatis
青梅味猪大肠5 小时前
【深入浅出C++】为什么虚表指针可以解决菱形继承
开发语言·c++
潘潘的嵌入式日记6 小时前
I²C 从机接收总被覆盖?双缓冲要在 STOP 时交接
c语言·开发语言·单片机