3. 友元类

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

友元类声明的语法

class 类名 {
   // 友元类的声明语法
   friend class 其他类名;
};

示例

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

// filename: friend3.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类的此类的友元类
    friend class Parent;
};

// 以下成员函数是类内声明,类外实现
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 friend3 friend3.cpp
weimz@mzstudio:~/old$ ./friend3
老张工作赚钱1000元
老张有钱1000元
小张有钱0元
老张给了小张700元钱
老张有钱300元
小张有钱700元