目录
一、背景
友元存在的作用:类成员有public,protected,private,成员类型为private时,只有类对象可以访问。而现在有个需求,需要外部的函数或类,可以访问这个类的private成员,友元就是解决这个问题的。可以理解为,把外部的函数或类,当作朋友,让其可以访问private成员。
具体用法是,在需要外部函数访问private的类内,通过friend关键字,声明外部函数或类是友元函数,指定其可以访问private成员变量。
二、友元函数
#include <iostream>
using namespace std;
class function
{
public:
function(int x,double y):
a(x),
b(y)
{
}
//声明友元函数
friend void otherFun(function*f);
private:
int a;
double b;
};
//其他函数必须讲该类作为入参传入
void otherFun(function*f)
{
cout << "其他函数读取function的私有成员,a=" << f->a << " b=" << f->b<<endl;
}
int main()
{
function*fun = new function(3,6.6);
otherFun(fun);
return 0;
}
三、友元类
#include <iostream>
using namespace std;
class function
{
public:
function(int x, double y) :
a(x),
b(y)
{
}
//声明友元类
friend class otherFun;
private:
int a;
double b;
};
//其他函数必须讲该类作为入参传入
class otherFun
{
public:
otherFun(function*f)
{
cout << "其他类读取function的私有成员,a=" << f->a << " b=" << f->b << endl;
}
};
int main()
{
function*fun = new function(3, 6.6);
otherFun* other = new otherFun(fun);
return 0;
}