第十一章、友元
在 C++ 的语法中,友元(friend)是指让声明的一个函数、类或成员函数可以访问该类的私有和保护成员。
友元的作用
让全局函数、其他类或其他类的成员函数可以访问该类的私有和保护成员。
友元是一种通过关键 friend 来实现的声明。
关键字
friend
1. 友元声明
友元声明的分类
- 友元函数
- 友元成员函数
- 友元类
语法
class 类名 {
// 友元函数的声明语法
friend 返回类型 友元函数名(形式参数列表);
// 友元成员函数的声明语法
friend 返回类型 其他类::类名友元函数名(形式参数列表);
// 友元类的声明语法
friend class 其他类;
};
示例
#include <iostream>
using namespace std;
class Children; // 类声明
class Parent{
public:
Parent(const string & n, int a)
: name(n),age(a),money(0){}
void work(int m);
void showInfo(void);
void giveMoneyTo(Children & c, int m); // 给孩子钱
private:
string name;
int age;
int money;
// 声明show_money函数可以访问本类的所有成员
friend void show_money(const Parent &);
friend class Children;
};
class Children {
public:
Children(const string & n, int a)
: name(n),age(a),money(0){}
void showInfo(void);
void borrowTo(Parent & p, int m);
private:
string name;
int age;
int money;
// 仅声明Parent类的giveMoneyTo函数可以访问本类的所有成员
friend void Parent::giveMoneyTo(Children & c, int m);
};
void Parent::work(int m) {
money += m;
}
void Parent::showInfo(void) {
cout << age << "岁的" << name << "有钱" << money
<< "元" << endl;
}
void Children::showInfo(void) {
cout << age << "岁的" << name << "有钱" << money
<< "元" << endl;
}
void Parent::giveMoneyTo(Children & c, int m) {
if (m > this->money) {
cout << "钱不够" << endl;
return;
}
this->money -= m;
c.money += m;
}
void Children::borrowTo(Parent & p, int m) {
if (m > this->money) {
cout << "本宝宝没钱,不借" << endl;
return;
}
this->money -= m;
p.money += m;
}
// 全局函数,用来打印家长的钱数;
void show_money(const Parent & p) {
cout << p.age << "岁的" << p.name << "有钱"
<< p.money << "元" << endl;
}
int main(int argc, char * argv[]) {
Parent p("老张", 31);
Children c("小张", 12);
p.work(1000);
show_money(p);
p.giveMoneyTo(c, 700);
p.showInfo();
c.showInfo();
c.borrowTo(p, 200);
p.showInfo();
c.showInfo();
return 0;
}