代码点读机 / C++ / friend

friend C++ · 关键字

友元声明,授权某个函数或类访问本类的 private 和 protected 成员,打破封装但要显式授权。

怎么用

friend 函数声明; 或 friend class 类名;

小例子

class 钱包 {
  int 余额 = 100;
  friend void 查看(const 钱包&);
};
void 查看(const 钱包& w) {
  std::cout << w.余额;
}
钱包 w; 查看(w);

运行结果

100

提醒:友元不是成员函数,不能继承,也不能用 this

官方文档:https://en.cppreference.com/w/cpp/language/friend

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← C++全部词条