友元



1友元:C++控制类对象私有部分的访问,但有时候需要在类的外部访问类的私有成员,这种情况下C++提供了友元机制。

  创建友元函数步骤:

  A:将函数声明放到类的声明中,并在原型前加上关键字friend

friend 返回值 函数名称(参数列表);

friend classclassname;

  B:编写友元函数定义,不需要再定义中使用关键字friend.

   friend int 友元函数名(const classname &a);

#include <iostream>

 

using namespace std;

 

class demo

{

private:

    int i;//只能在类的内部访问

public:

    demo() //构造函数

    {

       cout << "demo" << this << endl;

    }

    demo(const demo &it) //拷贝构造

    {

       //一旦自己实现了拷贝构造函数,类成员之间的赋值就需要自己完成,编译器不管了

       this->i = it.i;

       cout << "copy demo" << this << endl;

    }

    ~demo()

    {

       cout << "~demo" << this << endl;

    }

    void set_i(int i)

    {

       this->i = i;

    }

    int get_i()

    {

       return i;

    }

    //意思是声明一个该类的友元函数,该函数可以调用本类的信息

    friend void test();

    //意思是声明一个该类的友元,该类的信息可以被下面的类调用

    friend class demo1;

    //demodemo0互为友元

    friend class demo0;

};

 

void test()

{

    //因为这个函数时上面的

    demo d;

    //这里d.i就是demo中的私有的变量,由于使用了友元,所以test可以使用了

    d.i = 100;

    printf("%d\n",d.i);

}

 

class demo0

{

private:

    int i;

public:

    demo0()

    {

       demo d;

       d.i = 123;

       //打印出了123,说明友元中的类可以访问类中变量

       printf("%d\n",d.i);

    }

};

 

class demo1

{

public:

    demo1()

    {

       demo d;

       d.i = 144;

       printf("%d\n",d.i);

    }

    friend class demo2;

};

 

//通过下面的例子得出:我的朋友的朋友,不会是我的朋友

class demo2

{

public:

    demo2()

    {

       demo d;

       //这一句不能放开,如果放开了报错

       //d.i = 155;

    }

};

 

int main(void)

{

    test();

 

    demo0 d0;

 

    demo1 d1;

 

    //下面运行的时候报错了,说明友元的一个特点:我的朋友的朋友,不会是我的朋友

    //demo2 d2;

 

    return 0;

}

2.运行截图:

3.友元关系说明图

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涂作权的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值