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

2. 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;
}

运行结果:

友元函数

#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;
}

运行结果:

原文地址:https://www.cnblogs.com/bwjblogs/p/13024532.html