为什么要通过非成员运算符调用成员运算符功能?

时间:2019-01-09 14:19:53

标签: c++ overloading operator-keyword

我正在为模拟复数的类测试一些运算符重载,然后注意到,如果有两个相似的运算符函数执行完全相同的操作,一个是成员,另一个是非成员运算符,成员函数将被调用,而不是非成员函数。如果删除成员函数,则将调用非成员函数。为什么会这样?

#include<iostream>
using namespace std;

class Complex {
    private:
        double re, im;
    public:
        Complex(double _re, double _im): re(_re), im(_im) {}
        // Member operator, Complex = Complex + double
        Complex operator + (double n){
            cout << "Member" << endl;
            return(Complex(re + n, im));
        }
        friend ostream & operator << (ostream & output, const Complex z);
        friend Complex operator + (const Complex & a, const Complex & b);
        friend Complex operator + (const Complex & a, double n);
};

// Output for Complex objects
ostream & operator << (ostream & output, const Complex z){
    output << z.re << (z.im > 0 ? "+" : "") << z.im << "i";
    return output;
}

// Non member operator +, Complex = Complex + Complex
Complex operator + (const Complex & a, const Complex & b){
    return(Complex(a.re + b.re, a.im + b.im));
}

// Non member operator +, Complex = Complex + double
Complex operator + (const Complex & a, double n){
    cout << "Non member" << endl;
    return(Complex(a.re + n, a.im));
}

int main(){
    cout << Complex(1, 2) + Complex(2, 3) << endl;
    cout << Complex(1, 2) + 5.4 << endl; // Member operator is called
    return 0;
}

0 个答案:

没有答案