《新标准C++程序设计》4.4(C++学习笔记14)

运算符重载为友元函数

一般情况下,将运算符重载为类的成员函数,是较好的选择。 

但有时,重载为成员函数不能满足使用要求,重载为普通函数,又不能访问类的私有成员,所以需要将运算符重载为友元。

class Complex
{
double real,imag;
public:
Complex( double r, double i):real(r),imag(i){ };
Complex operator+( double r );
};
Complex Complex::operator+( double r )
{ //能解释 c+5
return Complex(real + r,imag);
}

经过上述重载后:

Complex c ;
c = c + 5; //有定义,相当于 c = c.operator +(5);

但是:

c = 5 + c; //编译出错

所以,为了使得上述的表达式能成立,需要将 + 重载为普通函数。

Complex operator+ (double r,const Complex & c)
{ //能解释 5+c
return Complex( c.real + r, c.imag);
}

但是普通函数又不能访问私有成员,所以,需要将运算符 + 重载为友元。

class Complex
{
double real,imag;
public:
Complex( double r, double i):real(r),imag(i){ };
Complex operator+( double r );
friend Complex operator + (double r,const Complex & c);
};
原文地址:https://www.cnblogs.com/cyn522/p/12301033.html