友元解析

不废话,先上一段代码:

#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声明即可)。

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