运算符重载为友元
通常,将运算符重载为
类的成员函数
重载为友元函数的情况:
成员函数不能满足使用要求
普通函数,又不能访问类的私有成员
一方面要让他像普通函数来完成一些工程,但是另外一方面呢,又希望他能够访问类的私有成员。
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; //OK
但是:
c = 5+c;//error
为了让上面的表达式成立,需要将+重载为普通函数
Complex operator+(double r,const Complex &c){ //能解释5+c
return Complex(c.real + r, c.imag); //但是由于real和imag是private的成员变量,所以如下面修改类的定义。
}
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);
};