前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >c++之友元

c++之友元

作者头像
西西嘛呦
发布2020-08-26 15:56:43
2900
发布2020-08-26 15:56:43
举报

客厅:客人可以随意走动;卧室:只有自己能进去;

现在想要自己的好朋友可以进去,就需要用到友元技术。即友元的目的就是让一个函数或者类访问另一个类中私有成员。

关键字:friend

三种实现方法:

  • 全局函数做友元
  • 类做友元
  • 成员函数做友元

全局函数做友元:

代码语言:javascript
复制
#include<iostream>
using namespace std;
class Building{
    friend void goodGay(Building* building);
public:
    Building() {
        room = "客厅";
        myRoom = "卧室";
    }
public:
    string room;
private:
    string myRoom;
};
//全局函数
void goodGay(Building *building) {
    cout << "好朋友正在访问" <<building->room<< endl;
    //如果不将dooGay变成Building的友元函数,这里就会报错
    cout << "好朋友正在访问" << building->myRoom << endl;
}
void test() {
    Building building;
    goodGay(&building);
}
int main() {
    test();
    system("pause");
    return 0;
}

类做友元:

说明:在类外定义成员函数时,需要先在类中声明函数。利用类名::函数名(),可以定义类的成员函数。

代码语言:javascript
复制
#include<iostream>
using namespace std;

class Building{
    friend class GoodGay;
public:
    string room;
    Building();
private:
    string myRoom;
};
//类外写成员函数
Building::Building() {
    room = "客厅";
    myRoom = "卧室";
}

class GoodGay {
public:
    Building* building;
    GoodGay();
    void visit();
};
GoodGay::GoodGay() {
    building = new Building();
}
void GoodGay::visit() {
    cout << "好基友类正在访问:" << building->room << endl;
    cout << "好基友类正在访问:" << building->myRoom << endl;
}
void test() {
    GoodGay gg;
    gg.visit();
}
int main() {
    test();
    system("pause");
    return 0;
}

成员函数做友元:

代码语言:javascript
复制
#include<iostream>
using namespace std;
class Building;
class GoodGay;

//要先定义GoodGay类。。。
//我尝试在Building之后定义,就不行,之前也先声明了这两个类
class GoodGay {
public:
    GoodGay();
    void visit();//让该函数可以访问Building的私有成员
    void visit2();
private:
    Building* building;
};

class Building{
    friend void GoodGay::visit();
public:
    string room;
    Building();
private:
    string myRoom;
};
//类外写成员函数
Building::Building() {
    room = "客厅";
    myRoom = "卧室";
}

GoodGay::GoodGay() {
    building = new Building();
}
void GoodGay::visit() {
    cout << "好基友类正在访问:" << building->room << endl;
    cout << "好基友类正在访问:" << building->myRoom << endl;
}
void GoodGay::visit2() {
    cout << "好基友类正在访问:" << building->room << endl;
    //cout << "好基友类正在访问:" << building->myRoom << endl;
}
void test() {
    GoodGay gg;
    gg.visit();
}
void test2() {
    GoodGay gg;
    gg.visit2();
}
int main() {
    test();
    system("pause");
    return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-12-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档