一般情况下,将运算符重载为类的成员函数,是较好的选择。
但有时,重载为成员函数不能满足使用要求,重载为普通函数,又不能访问类的私有成员,所以需要将运算符重载为友元。
如重载为成员函数时,他不能处理5+c的情况
如下,定义一个复数类
创建 复数对象a,对a进行运算
class Complex {
double real, imag;
public :
Complex(double r, double imag) :real(r), imag(imag) {};
Complex operator+(double r);
};
Complex Complex::operator+(double r) {//可以解释a+5
return Complex(r + real, imag);
}
int main() {
Complex a(1,2);
a = a + 5;//等价于a.operator+(5);
a = 5 + a;//报错
}
根据使用需求,所以我们应该把运算符号重载为普通函数好些
但是普通函数又不能访问私有成员,所以,需要将运算符+重载为友元。
friend Complex operator+(double r, const Complex& s);//友元
普通函数实现:
Complex operator+(double r, const Complex& s) {//普通函数
return Complex(r + s.real,s.imag);
}
完整代码:
class Complex {
double real, imag;
public :
int GetReal() { return real; }
int Getimag() { return imag; }
Complex(double r, double imag) :real(r), imag(imag) {};
Complex operator+(double r);
friend Complex operator+(double r, const Complex& s);//友元
};
Complex Complex::operator+(double r) {//可以解释a+5
return Complex(r + real, imag);
}
Complex operator+(double r, const Complex& s) {//普通函数
return Complex(r + s.real,s.imag);
}
int main() {
Complex a(1,2);
a = a + 5;//等价于a.operator+(5);
a = 5 + a;//ok了
cout << a.GetReal() << "," << a.Getimag() << endl;
}
运行结果: