C++中声明友元

文章介绍了C++中如何通过`friend`关键字声明友元,使外部函数或类能访问私有数据成员。实例展示了友元函数和友元类如何突破常规访问限制,提供对类内部信息的访问权限。
摘要由CSDN通过智能技术生成

C++中声明友元

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

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

#include <iostream>
#include <string>
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 <iostream>
#include <string>
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 类的私
有数据成员和方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值