關於C++友元


雖然C++的友元破壞了類的封裝特性,但是它使得訪問一個類的內部私有成員成爲可能。

一個函數不僅可以是一個類類的友元,也可是是多個類的友元,需要在指定的類中使用關鍵字friend聲明。

通過下面的例子來理解。

#include <iostream>
using namespace std;

class Journey; // 前向引用Journey類,因爲MyDate類中聲明友元函數的時候引用了該類Journey。

class MyDate{
    int year;
    int month;
    int day;
public:
    MyDate(int year,int month,int day){
        this->year = year;
        this->month = month;
        this->day = day;    
    }
    int getYear(){
        return this->year;
    }
    int getMonth(){
        return this->month;
    }
    int getDay(){
        return this->day;
    }    
    void displayMyDate() const{
        cout << year << "年" << month << "月" << day << "日" << endl;
    }
    friend void getMyJourney(MyDate myDate,Journey journey); //聲明友元
};

class Journey{
    string personName;
    string startSite;
    string arriveSite;
public:
    Journey(string personName,string startSite,string arriveSite){
        this->personName = personName;
        this->startSite = startSite;
        this->arriveSite = arriveSite;
    }
    void displayJourney() const{
        cout << personName << "旅行,從" << startSite << "出發,去了" << arriveSite << "。" << endl;
    }
    friend void getMyJourney(MyDate myDate,Journey journey); //聲明友元
};

void getMyJourney(MyDate myDate,Journey journey){
    cout << journey.personName << "旅行,於" << myDate.getYear() << "年" << myDate.getMonth() << "月" << myDate.getDay() << "日從" << journey.startSite << "出發,去了" << journey.arriveSite << "。" << endl;
}

int main(){
    MyDate md(2008,7,28);
    md.displayMyDate();
    Journey jour("Shirdrn","長春","洛杉磯");    
    jour.displayJourney();
    getMyJourney(md,jour); // 調用友元函數
    return 0;
}

運行結果:

2008年7月28日
Shirdrn旅行,從長春出發,去了洛杉磯。
Shirdrn旅行,於2008年7月28日從長春出發,去了洛杉磯。

在上面的程序中,可以觀察void getMyJourney(MyDate myDate,Journey journey)函數:

void getMyJourney(MyDate myDate,Journey journey){
    cout << journey.personName << "旅行,於" << myDate.getYear() << "年" << myDate.getMonth() << "月" << myDate.getDay() << "日從" << journey.startSite << "出發,去了" << journey.arriveSite << "。" << endl;
}

在輸出一個Journey的時候,並沒有通過MyDate類的getXXX方法獲取私有數據,而是直接通過訪問私有成員得到了它的數據;而Journey類本身就沒有提供公共的getXXX方法,也是直接訪問它的私有成員獲得它的數據內容。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章