C++ 访问私有成员——友元函数和友元类

我们之前说到过,一个类中的私有成员变量或者函数,在类外是没有办法被访问的。但是,如果我们必须要访问该怎么办呢?这就要用到友元函数或者友元类了。

而友元函数和友元类,就相当于一些受信任的人。我们在原来的类中定义友元函数或者友元类,告诉程序:这些函数可以访问我的私有成员。

C++通过过friend关键字定义友元函数或者友元类。

友元类

  1. Date.h
#ifndef DATE_H
#define DATE_H

class Date {
public:
    Date (int year, int month, int day) {
        this -> year = year;
        this -> month = month;
        this -> day = day;
    }
    friend class AccessDate;

private:
    int year;
    int month;
    int day;
};
#endif // DATE_H
  1. main.cpp
#include <iostream>
#include "Data.h"

using namespace std;

class AccessDate {
public:
    static void p() {
        Date birthday(2020, 12, 29);
        birthday.year = 2000;
        cout << birthday.year << endl;
    }
};

int main()
{
    AccessDate::p();
    return 0;
}

运行结果:

C++ 访问私有成员——友元函数和友元类

友元函数

#include <iostream>

using namespace std;

class Date {
public:
    Date (int year, int month, int day) {
        this -> year = year;
        this -> month = month;
        this -> day = day;
    }
    friend void p();

private:
    int year;
    int month;
    int day;
};

void p() {
    Date birthday(2020, 12, 29);
    birthday.year = 2000;
    cout << birthday.year << endl;
}

int main()
{
    p();
    return 0;
}

运行结果:

C++ 访问私有成员——友元函数和友元类
原文链接: https://www.cnblogs.com/bwjblogs/p/13024532.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/198227

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午7:48
下一篇 2023年2月12日 下午7:48

相关推荐