友元函数 friend

 全局函数做友元函数

全局函数写到类中做声明 并且使用友元函数关键字friend

实现

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;

class House
{
    friend void GoodGay(House * h);        //添加好基友函数作为友元函数
public:
    House()
    {
        this->m_SittingRoom = "客厅";
        this->m_BedRoom = "卧室";
    }
    string m_SittingRoom;    //客厅
private:
    string m_BedRoom;        //卧室
};

void GoodGay(House* h)
{
    cout << "好基友访问" << h->m_SittingRoom << endl;
    cout << "好基友访问" << h->m_BedRoom << endl;    //因为m_BedRoom是私有属性 所以无法访问
}
void test301()
{
    House * h = new House;
    GoodGay(h);
}

int main()
{
    test301();
    system("Pause");        //阻塞功能
    return EXIT_SUCCESS;    // 返回正常退出
}

变成友元函数的全局函数GoodGay()就可以访问私有属性了

原文地址:https://www.cnblogs.com/yifengs/p/15170823.html