您的位置:首页 > 编程语言 > C语言/C++

C++之友元函数

2016-07-17 22:23 288 查看
友元函数(friend)

如果不属于当前结构的一个函数想访问当前的结构中的数据,那么就要用友元函数。

注意:friend必须要在结构中声明。

友元函数的实现:

#include<iostream>

using namespace std;

class Test;

void fun(Test x);

class Test

{

    friend void fun(Test x);     //声明函数friend

public: //公有的

    Test(int d=0) //初始化

    {

data = d;

}

private: //私有的

    int data;

};

void fun(Test x)

{

    int value = x.data; //调用初始化构造函数

cout << x.data<<endl; //打印函数执行结果

}

int main()

{

    Test t(100);

    fun(t);

    return 0;

}

注:在使用友元函数时,必须要声明friend,否则无法调用,但是出现这种情况,A是友元函数,在B中声明,程序可以运行正确,但是B如果调用A中的函数,运行就会错误,所以B用A时也必须声明friend。

#include<iostream>

using namespace std;

 

class B;

 

class A

{

    friend class B;

public:

    void fun(B b);

private:

    int x;

};

 

class B

{

    friend class A;

public:

    void list(A a)

    {

        a.x;

    }

private:

    int y;

};

 

void A::fun(B b)

{

    b.y;

}

 

int main()

{

    A aa;

    B bb;

    aa.fun(bb);

}

 

4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: