首页 > 解决方案 > 全局函数与类方法之间的c ++运算符重载区别

问题描述

我有 Java 背景并尝试学习 C++。我有如下所示的代码。我试图了解什么时候应该像这样重载运算符complex operator+(const complex& c2),什么时候应该像这样重载运算符complex operator+(complex a, complex b)。我不能同时拥有这两个函数,因为编译器抱怨歧义,所以我已经注释掉了一个。两个函数(前者是类的方法)产生相同的结果:

#include <iostream>
using namespace std;

//This class is in global scope
class complex {
    private:
        double re, im;

    public: 
        complex(double r, double i): re {r}, im {i} {}
        double real() const { 
            return re;
        }
        void real(double r) {
            re = r;
        }

        double imag() const { 
            return im;
        }
        void imag(double i) {
            im = i; 
        }

        /*
        complex operator+(const complex& c2) {
            cout << "Single arg operator+\n";
            complex c = complex(0, 0);
            c.real(re + c2.real());
            c.imag(im + c2.imag());
            return c;
        }
        */

        complex& operator+=(const complex& c2) {
            cout << "operator+=\n";
            re += c2.real();
            im += c2.imag();
            return *this;
        }

        void print() {
            cout << "Real: " << re << ", Imaginary: " << im << "\n";
        }
};

//This function is in global scope
complex operator+(complex a, complex b) {
    cout << "Double arg operator+\n";
    return a += b;
}

int main() {
    complex c = complex(2, 3);
    complex c2 = complex(2, 3);
    complex c3 = c + c2;
    c.print();
    c += c2;
    c.print();
}

标签: c++

解决方案


推荐阅读