在 C++ 中,类 的私有成员(private)和只能在本类中访问,类的保护成员(protected)只能在本类或者子类中访问,但类的友元函数可以访问类的私有成员和保护成员。
类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是 成员函数。
使用 friend 修饰的函数,称为友元函数。
class ClassName
{
public:
friend void func();
};
void func()
{
}
我们使用 friend 定义了一个友元函数 func。
C++ 友元函数,可以访问类的私有成员
#include <iostream>
using namespace std;
class Student
{
public:
Student(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
void sayHello() const
{
cout << "I am " << this->m_name << " and i am " << this->m_age << " years old!" << endl;
}
private:
string m_name;
int m_age;
};
//非成员函数
void show(Student stu)
{
cout << "Call Show, Name =" << stu.m_name << " Age = " << stu.m_age << endl;
}
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
Student stu("HaiCoder", 111);
show(stu);
return 0;
}
程序运行后,控制台输出如下:
我们在类的外面使用 show 函数,访问类的私有成员,结果程序报错,因为类的私有成员只有在类的内部可以访问,现在,我们将函数声明为友元函数,修改程序如下:
#include <iostream>
using namespace std;
class Student
{
public:
Student(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
void sayHello() const
{
cout << "I am " << this->m_name << " and i am " << this->m_age << " years old!" << endl;
}
friend void show(Student stu);
private:
string m_name;
int m_age;
};
//非成员函数
void show(Student stu)
{
cout << "Call Show, Name =" << stu.m_name << " Age = " << stu.m_age << endl;
}
int main()
{
cout << "嗨客网(www.haicoder.net)\n" << endl;
Student stu("HaiCoder", 111);
show(stu);
return 0;
}
程序运行后,控制台输出如下:
这次,我们将函数 show 声明为了友元函数,这次,我们可以在友元函数里面访问类的私有成员了。
类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。