运算符重载为非成员函数的规则:
- 函数的形参代表依自左至右次序排列的各操作数
- 重载为非成员函数时
- 参数个数 = 原操作数个数(后置++、--除外,它们仍然为了区分前置++、--要强行加个int)
- 至少应该有一个自定义类型的参数(例如"Typ1 operator + (int, double)"非法)
- 如果在运算符的重载函数中需要操作某类对象的私有成员,可以将此函数声明为该类的友元
运算符重载为非成员函数的使用方法:
- 重载双目运算符U:oprd1 U oprd2 = operator U (oprd1, oprd2)
- 前置单目运算符U:U oprd = operator U(oprd)
- 后置单目运算符U:oprd U = operator U(oprd, 0)
例子:重载负数的加减法以及"<<"运算符:
- 将+、-重载为非成员函数,并将其声明为复数类的友元,两个操作数都是复数类的常引用
- 将<<(双目运算符)重载为非成员函数,并将其声明为复数类的友元,它的左操作数是std::ostream引用,右操作数为复数类的常引用,返回std::ostream引用
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(double r = 0.0, double i = 0.0): r(r), i(i) {}
friend Complex operator + (const Complex &c1, const Complex &c2);
friend Complex operator - (const Complex &c1, const Complex &c2);
friend ostream &operator << (ostream &out, const Complex &c);
private:
double r;
double i;
};
Complex operator + (const Complex &c1, const Complex &c2)
{
return Complex(c1.r+c2.r, c1.i+c2.i);
}
Complex operator - (const Complex &c1, const Complex &c2)
{
return Complex(c1.r-c2.r, c1.i-c2.i);
}
ostream &operator << (ostream &out, const Complex &c)
{
out<<"("<<c.r<<", "<<c.i<<")";
return out;
}
int main(void)
{
Complex c1(5, 4), c2(2, 10), c3;
c3 = c1 - c2;
cout<<"c3 = c1 - c2 = "<<c3<< endl;
c3 = c1 + c2;
cout<<"c3 = c1 + c2 = "<<c3<< endl;
return 0;
}