利用友元机制,允许将一个类的私有数据的访问权授予指定的其他函数或类。如果将该特权赋予一个普通函数,该函数称为该类的友元函数;如果将这种特权赋予另外一个类,该类就称为友元类。
声明友元函数的方式是在类中使用关键字friend,格式如下:
friend 函数类型 友元函数名(参数表);
说明:
- 声明友元函数的位置可以在类的任何地方,不受访问权限的限制。声明时,既可以放在public区,也可以放在private区或protected区。
- 在类内完成友元函数的声明,而在类外完成友元函数的定义。
- 定义友元函数时,函数首部不再需要关键字friend。
声明为一个类的友元函数后,就可以在该函数中直接访问该类的私有数据。需要注意的是,这样做并没有使类的数据成为公有的,未经授权的其他函数仍然不能直接访问这些私有数据。
下面通过一个程序例子来说明。
#include <iostream>
using namespace std;
class Student
{
private:
int grade;
public:
char name[20];
void set(char* NameStr, int StuGrade)
{
int i = 0;
while((*NameStr!= '\0') && i < 20){
name[i] = *NameStr;
i++;
NameStr++;
}
name[i] = *NameStr;
grade = StuGrade;
}
friend char *ReturnName(Student);
};
char *ReturnName(Student S1)
{
if(S1.grade >= 80)return S1.name;
else return NULL;
}
int main(int argc, _TCHAR* argv[])
{
Student a, b, c, d;
a.set("Kevin", 65);
b.set("Allen", 75);
c.set("William", 85);
d.set("Curry", 95);
if(ReturnName(a)!=NULL)cout<<a.name<<endl;
if(ReturnName(b)!=NULL)cout<<b.name<<endl;
if(ReturnName(c)!=NULL)cout<<c.name<<endl;
if(ReturnName(d)!=NULL)cout<<d.name<<endl;
system("pause");
return 0;
}
程序运行结果:
如果将char name[20]修改为private类型,则编译不过。因为不允许在Student的友元函数之外main函数访问该类的私有的数据。