友元解析

不廢話,先上一段代碼:

#include <iostream>

class Person{
private:
    int age;
public:
    Person(int age){
        this->age = age;
    }
};

void printAge(Person const &person){
    std::cout << person.age << std::endl;
}

int main(){
    Person alice = Person(24);
    printAge(alice);    //ERROR
    return 0;
}

很明顯,由於age是private的變量,所以外部的printAge無法訪問,如何訪問呢?再看看下面一段代碼:

#include <iostream>

class Person{
private:
    int age;
    friend  void printAge(Person const &person);    //New line.
public:
    Person(int age){
        this->age = age;
    }
};

void printAge(Person const &person){
    std::cout << person.age << std::endl;
}

int main(){
    Person alice = Person(24);
    printAge(alice);        //Correct
    return 0;
}

友元函數總結:

友元函數是可以訪問private變量的非成員函數。友元函數的定義在全局域,不屬於任何類(所以沒有this指針),不過需要在作用類中加friend聲明(聲明可以放在private,也可以放在public)。

一個函數可以同時成爲多個類的友元函數(只要在各個類中都有friend聲明即可)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章