C++ 友元 学习笔记

#include <iostream>
//友元的三种实现
    //全局函数做友元
    //类做友元
    //成员函数做友元
using namespace std;


全局函数做友元
一般来说,在全局函数中实例化类的对象后 可以访问该类的公共成员属性和成员函数
但是在某些特定的场景需要访问该类的私有成员 这个时候可以用友元关键字friend声明
在该类的首句中写 friend 全局函数name  eg: friend void test01(int age);

//class Building
//{
//    friend void test01();
//public:
//    Building()
//    {
//        settingroom = "客厅";
//        badroom = "卧室";
//    }
//    string settingroom;
//private:
//    string badroom;

//};

//void test01()
//{
//    Building building;
//    cout << "你的好基友正在访问" << building.settingroom << endl;
//    cout << "你的好基友正在访问" << building.badroom << endl;
//}

//int main()
//{
//    test01();
//    cout << "Hello World!" << endl;
//    return 0;
//}


//类做友元

class Building
{
    friend class GoodGay;
public:
    Building()
    {
        settingroom = "客厅";
        bedroom = "卧室";
    }
    string settingroom;
private:
    string bedroom;

};

class GoodGay
{
public:
    GoodGay()
    {
        building = new Building; //new 在堆区开辟内存空间 返回对象指针
    }
    void visit()
    {
        cout << "好基友类正在访问:" << building->settingroom << endl;
        cout << "好基友类正在访问:" << building->bedroom << endl;
    }

    Building * building;
};

void test01()
{
    GoodGay gg;
    gg.visit();
}

int main()
{
    test01();
    cout << "Hello World!" << endl;
    return 0;
}


成员函数做友元
//class Building;
//class GoodGay
//{
//public:
//    GoodGay()
//    {
//        building = new Building; //new 在堆区开辟内存空间 返回对象指针
//    }
//    void visit01()
//    {
//        cout << "好基友类正在访问:" << building->settingroom << endl;
//        cout << "好基友类正在访问:" << building->bedroom << endl;
//    }
//    void visit02()
//    {
//        cout << "好基友类正在访问:" << building->settingroom << endl;
//        cout << "好基友类正在访问:" << building->bedroom << endl;
//    }

//    Building * building;


//};

//class Building
//{
//    friend void GoodGay::visit01();
//public:
//    Building()
//    {
//        settingroom = "客厅";
//        bedroom = "卧室";
//    }
//    string settingroom;
//private:
//    string bedroom;

//};



//void test01()
//{
//    GoodGay gg;
//    gg.visit01();
//    gg.visit02();
//}

//int main()
//{
//    test01();
//    cout << "Hello World!" << endl;
//    return 0;
//}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值