《C++程序设计教程》笔记之类友元

live long and prosper

《C++程序设计教程》笔记之类友元

在C++语言中,类也可以作为友元。
在下面例子中,创建了一个B类和G类。
B类中含有两个属性,sittingroom是公共属性,livingroom是私有属性。在G类中创建一个B类,并能够访问B类中的元素。

1、无友元,访问公共和私有属性

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

class B;

class G{
public:
    B *building;
    G();
public:
    void visit();
};

class B{
    class G;
public:
    B(){
        sittingroom="sittingroom";//客厅
        livingroom="livingroom";//卧室
    }
public:
    string sittingroom;//客厅作为公共属性
private:
    string livingroom;//卧室作为私有属性
};

G::G() {
    building=new B;
}

void G::visit() {//访问B类中的元素
    cout<<"---"<<building->sittingroom<<endl;
    cout<<"---"<<building->livingroom<<endl;
}

void test01(){//测试函数,验证visit()函数
    G gg;
    gg.visit();
}

int main()
{
    test01();
    return 0;
}

在这个例子中,让visit()函数访问B中的公共函数和私有属性,结果编译器报错:

‘std::string B::livingroom’ is private within this context
visit()函数无法访问私有变量

2、建立友元

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

class B;

class G{
public:
    B *building;
    G();
public:
    void visit();
};

class B{
    friend class G;//在B类中,建立G的友元类,让B类对G类“友好”
public:
    B(){
        sittingroom="sittingroom";
        livingroom="livingroom";
    }
public:
    string sittingroom;
private:
    string livingroom;
};

G::G() {
    building=new B;
}

void G::visit() {
    cout<<"---"<<building->sittingroom<<endl;
    cout<<"---"<<building->livingroom<<endl;
}

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

int main()
{
    test01();
    return 0;
}

编译结果为:

—sittingroom
—livingroom

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值