友元函数声明在类中,可以访问类中的私有成员,但不能通过 . 或 -> 调用
使用友元函数重载运算符
#include <iostream> using namespace std; class Father { private: int a; int b; friend Father operator*(int value, const Father &father); //放在 private 中也可以 public: Father(){} Father(int x, int y):a(x), b(y){} }; Father operator*(int value, const Father &father) { Father tmp; tmp.a = father.a * value; tmp.b = father.b * value; return tmp; } int main() { Father father(1,2); father = 2 * father; return 0; }