2. 友元成员函数

友元成员函数是指声明其他类的一个或多个成员函数作为该类的特殊函数,这些函数可以访问该类的私有或保护成员。

友元成员函数声明的语法

class 类名 {
   // 友元成员函数的声明语法
   friend 返回类型 其他类名::成员函数名(形式参数列表);
};

示例

让 Parent 类的 giveMoneyTo 成员函数成为 Children 类的友元成员函数,让 giveMoneyTo 能够访问 Children 类的全部成员。

// filename: friend2.cpp
#include <iostream>

class Children; // 类声明
class Parent{
    public:
        Parent(const std::string & n);
        void work(int m);
        void showInfo(void);
        void giveMoneyTo(Children & c, int m); // 给孩子钱
    private:
        std::string name;
        int money;
};

class Children {
    public:
        Children(const std::string & n);
        void showInfo(void);
    private:
        std::string name;
        int money;
    // 声明Parent类的giveMoneyTo函数可以访问此类的所有成员
    friend void Parent::giveMoneyTo(Children & c, int m);
};

// 以下成员函数是类内声明,类外实现
Parent::Parent(const std::string & n) : name(n), money(0){
}

void Parent::work(int m) {
    std::cout << name << "工作赚钱" << m << "元" << std::endl;
    money += m;
}

void Parent::showInfo(void) {
    std::cout << name << "有钱" << money << "元" << std::endl;
}

void Parent::giveMoneyTo(Children & c, int m) {
    if (m > this->money) {
        std::cout << "钱不够" << std::endl;
        return;
    }
    this->money -= m;
    c.money += m;
    std::cout << name << "给了" << c.name << m << "元钱" << estd::ndl;
}
Children::Children(const std::string & n) : name(n),money(0){
}
void Children::showInfo(void) {
    std::cout << name << "有钱" << money << "元" << std::endl;
}

int main(int argc, char * argv[]) {
    Parent p("老张");
    Children c("小张");
    p.work(1000);
    p.showInfo();
    c.showInfo();
    p.giveMoneyTo(c, 700);
    p.showInfo();
    c.showInfo();

    return 0;
}

编译和运行结果如下:

weimz@mzstudio:~/old$ g++ -o friend2 friend2.cpp
weimz@mzstudio:~/old$ ./friend2
老张工作赚钱1000元
老张有钱1000元
小张有钱0元
老张给了小张700元钱
老张有钱300元
小张有钱700元