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

運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM