友元关系可以继承_C++知识点 30:友元

30.1 全局函数作为友元函数

全局函数本身只具有公共权限,无法访问私有属性
将全局函数友元化,可以访问类中的私有属性
友元语法: friend + 全局函数声明 // 放入类的最上方
****************************************************************************************
#define _CRT_SECURE_NO_WARNINGS
#include
using namespace std;
#include// 全局函数作为友元函数:使全局函数可以访问类中的私有属性
class Buliding
{
friend void GoodGay(Buliding &buliding); // 全局函数友元化
public:
Buliding() // 默认构造函数: 初始化成员变量
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
string m_SittingRoom; // 客厅: 公共属性
private:
string m_BedRoom; // 卧室: /私有属性
};------------------------------------------------------------------------------------------
void GoodGay(Buliding &buliding) //全局函数
{
cout << "好基友正在访问: " << buliding.m_SittingRoom << endl; // 访问公共属性 -- OK
// cout << "好基友正在访问: " << buliding.m_BedRoom << endl; //访问私有属性 -- err// 解决:将全局函数友元化
// 用法: friend + 全局函数声明 然后放入类的最上方

cout << "好基友正在访问: " << buliding.m_BedRoom << endl; // 友元后就可以了
}
int main()
{
Buliding b;
GoodGay(b);
system("pause");
return EXIT_SUCCESS;
}

30.2 类作为友元类
#define _CRT_SECURE_NO_WARNINGS
#include
using namespace std;
#include
class Building
{
friend class GoodGay; // 友元类的声明
public:
Building() // 默认构造函数
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
public:
string m_SittingRoom; // 公共属性: 客厅
private:
string m_BedRoom; // 私用属性: 卧室
};------------------------------------------------------------------------------------------
class GoodGay
{
public:
GoodGay() {
building = new Building; // 默认构造初始化 被友元类的指针
}
void visit()
{
cout << this->building->m_SittingRoom << endl;
// Building类对象指针是GoodGay的成员变量,因此可以访问Building类的共有属性变量
// cout << this->building->m_BedRoom << endl; //如果未设置友元类, err: m_BedRoom不可访问//解决方式:将 GoodGay 作为 Building 的友元类,可以访问 Building 中是私有属性
cout << this->building->m_BedRoom << endl;
}
private:
Building * building; // 维护着 被友元类的指针
};
void test()
{
GoodGay gg;
gg.visit();
}

int main()
{
test();
system("pause");
return EXIT_SUCCESS;
}// 注意:
// 友元关系不能被继承
// 友元类是单向的: 类A是类B的友元类,则类A可以访问类B中的私有属性,但类B不一定是类A的友元类
// 友元类不具有传递性: 类 A 是类 B 的友元类,类 B 是类 C 的友元类,类 A 不一定是类 C 的友元类

d894968257cb9d5f15dcc0fb21bf80b3.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值