运算符重载函数既可以声明为类的成员函数,也可以声明为所有类之外的全局函数。
将运算符重载函数声明为全局函数时,二元操作符需要两个参数,一元操作符需要一个参数,而其中必须有一个参数是对象,好让编译器区分这是程序员自定义的运算符。
以下例子是用全局运算符重载计算复数的和:
#include <iostream>
using namespace std;
class complex{
private:
double real; //实部
double imag; //虚部
public:
complex() : real(0.0), imag(0.0){ }
complex(double a, double b) : real(a), imag(b){ }
void display()const{ cout << real << " + " << imag << "i" << endl; }
friend complex operator+(const complex &A, const complex &B); //友元函数
};
//全局运算符重载
complex operator+(const complex &A, const complex &B){
complex C;
C.real = A.real + B.real;
C.imag = A.imag + B.imag;
return C;
}
int main(){
complex c1(4.3, 5.8);
complex c2(2.4, 3.7);
complex c3;
c3 = c1 + c2;
c3.display();
return 0;
}
结果:
因为重载运算符函数要用到 complex 类的私有变量,所以我们将该函数声明为友元函数。当执行:
c3 = c1 + c2;会被转换为:
c3 = operator+(c1, c2);