友元



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

  创建友元函数步骤:

  A:将函数声明放到类的声明中。并在原型前加上keywordfriend

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

friend classclassname;

  B:编写友元函数定义。不须要再定义中使用keywordfriend.

   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 ",d.i);

}

 

class demo0

{

private:

    int i;

public:

    demo0()

    {

       demo d;

       d.i = 123;

       //打印出了123。说明友元中的类能够訪问类中变量

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

    }

};

 

class demo1

{

public:

    demo1()

    {

       demo d;

       d.i = 144;

       printf("%d ",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.友元关系说明图

 

原文地址:https://www.cnblogs.com/mfmdaoyou/p/6709047.html