C++中声明友元

C++中声明友元

不能从外部访问类的私有数据成员和方法,但这条规则不适用于友元类和友元函数。要声明友元
类或友元函数,可使用关键字 friend,如以下示例程序所示:

使用关键字 friend 让外部函数 DisplayAge( )能够访问私有数据成员

#include 
#include 
using namespace std;

class Human
{
    private:
    friend void DisplayAge(const Human& person);
    string name;
    int age;

    public:
    Human(string humansName, int humansAge) 
    {
        name = humansName;
        age = humansAge;
    }
};

void DisplayAge(const Human& person)
{
    cout << person.age << endl;
}

int main()
{
    Human firstMan("Adam", 25);
    cout << "Accessing private member age via friend function: ";
    DisplayAge(firstMan);

    return 0;
}

输出:

Accessing private member age via friend function: 25

分析:
第 7 行的声明告诉编译器,函数 DisplayAge( )是全局函数,还是 Human 类的友元,因此能够访问
Human 类的私有数据成员。如果将第 7 行注释掉,第 22 行将导致编译错误。与函数一样,也可将外部类指定为可信任的朋友,如以下程序所示:

#include 
#include 
using namespace std;

class Human
{
private:
   friend class Utility;
   string name;
   int age;

public:
   Human(string humansName, int humansAge) 
   {
      name = humansName;
      age = humansAge;
   }
};

class Utility
{
public:
   static void DisplayAge(const Human& person)
   {
      cout << person.age << endl;
   }
};
   
int main()
{
   Human firstMan("Adam", 25);
   cout << "Accessing private member age via friend class: ";
   Utility::DisplayAge(firstMan);

   return 0;
}

输出:

Accessing private member age via friend class: 25

分析:
第 7 行指出 Utility 类是 Human 类的友元,该声明让 Utility 类的所有方法都能访问 Human 类的私
有数据成员和方法。

该文章会更新,欢迎大家批评指正。

推荐一个零声学院的C++服务器开发课程,个人觉得老师讲得不错,
分享给大家:Linux,Nginx,ZeroMQ,MySQL,Redis,
fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,
TCP/IP,协程,DPDK等技术内容
点击立即学习:C/C++后台高级服务器课程

你可能感兴趣的:(C++编程基础,c++)