C++中的友元

为什么要有友元?

一个全局函数或者类想访问另一个类私有的成员属性的时候,就要用到友元

关键词:friend

使用友元的三种情况

1.全局函数做友元

告诉我想访问的那个类,我是你们这个类的我的好朋友,可以让我访问私有成员属性

#include <iostream>
​
using namespace std;
class Building {
    friend void GoodFreind(Building& b);
    string bedroom;//私有的
public:
    string sittingroom;
    Building();//类内声明构造函数
    /*{
        this->bedroom = "卧室";
        this->sittingroom = "客厅";
    }*/
};
Building::Building() {
    this->bedroom = "卧室";
    this->sittingroom = "客厅";
}
void GoodFreind(Building& b) {//当全局函数想访问一个类中的私有成员属性的时候,把这个函数声明成友元函数就可以实现了
    cout << "朋友相进入" << b.sittingroom << endl;
    cout << "朋友想进入" << b.bedroom << endl;
}
​
int main() {
    Building b;
    GoodFreind(b);
    return 0;
}

2.类做友元

#include <iostream>
​
using namespace std;
​
class Building {
    friend Friend;//Friend类设为友元
    string bedroom;//私有的
public:
    string sittingroom;
    Building();//类内声明构造函数
};
class Friend {
    Building *b;
public:
    Friend();//类内声明构造函数
    ~Friend();
    void vist();
};
Building::Building() {
    this->bedroom = "卧室";
    this->sittingroom = "客厅";
}
Friend::Friend(){
    b = new Building();//成员变量指向堆区空间了,要调用析构函数
}
Friend::~Friend() {
    if(b) delete b;
}
void Friend::vist() {//一个类想访问另一个类的私有成员,把这个类变为友元
    cout << "朋友想进入" << b->sittingroom;
    cout << "朋友想进入" << b->bedroom;
}
int main() {
    Building b;
    return 0;
}

3.类中的成员函数做友元

#include <iostream>
​
using namespace std;
class Friend {
    Building* b;
public:
    Friend();//类内声明构造函数
    ~Friend();
    void vist();
};
class Building {
    friend void Friend::vist();//Friend类里面的成员函数设为友元
    string bedroom;//私有的
public:
    string sittingroom;
    Building();//类内声明构造函数
};
​
Building::Building() {
    this->bedroom = "卧室";
    this->sittingroom = "客厅";
}
Friend::Friend(){
    b = new Building();//成员变量指向堆区空间了,要调用析构函数
}
Friend::~Friend() {
    if(b) delete b;
}
void Friend::vist() {//一个类想访问另一个类的私有成员,把这个类变为友元
    cout << "朋友想进入" << b->sittingroom;
    cout << "朋友想进入" << b->bedroom;
}
int main() {
    Building b;
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值