'''
#include <iostream>
using namespace std;
class Complex{
int real;
int image;
public:
Complex(){
cout<<"default constructor is called"<<endl;
}
Complex(int r, int i=0){
real = r;
image = i;
cout<<"constructor is called"<<endl;
}
~Complex(){
cout<<"deconstructor is called"<<endl;
}
friend Complex operator+(const Complex &a, const Complex &b){
return Complex(a.real + b.real, a.image + b.image);
}
friend ostream &operator<<(ostream &o, const Complex &a){
o<<a.real<<"+"<<a.image<<"i";
}
};
int main() {
Complex a(5,6);
cout<<a+7<<endl;
cout<<"---------------------------------------"<<endl;
cout<<8+a<<endl;
return 0;
}
'''
以上述代碼為例子菊卷,當(dāng)需要對(duì)運(yùn)算符“+”進(jìn)行重載的時(shí)候缔恳,如果將重載函數(shù)寫成類的成員函數(shù),將只能實(shí)現(xiàn)a+7洁闰,而不能實(shí)現(xiàn)8+a歉甚。或者說扑眉,可以寫兩個(gè)全局重載函數(shù):
'''
Complex(int n, const Complex &a){
return Complex(a.real + n, a.imag);
}
Complex(const Complex &a, int n){
return Complex(a.real + n, a.imag);
}
'''
但是這兩個(gè)函數(shù)可以簡(jiǎn)化寫成一個(gè)函數(shù):
'''
Complex operator+(const Complex &a, const Complex &b){
return Complex(a.real + b.real, a.image + b.image);
}
'''
這樣a+8 或者 7+a在運(yùn)行的時(shí)候纸泄,首先會(huì)調(diào)用構(gòu)造函數(shù)將8或7表示成一個(gè)臨時(shí)的Complex對(duì)象,然后再調(diào)用運(yùn)算符重載函數(shù)腰素。