友元函数(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);
}
本文介绍了C++中的友元函数概念及其使用方式。通过实例详细解释了如何声明和使用友元函数来访问类的私有成员,并展示了两个类互相作为对方友元的情况。
1万+

被折叠的 条评论
为什么被折叠?



