如何用类的参数重载运算符 +?

son*_*s10 0 c++ oop class operator-overloading object

我正在学习 C++ 中的重载运算符,并且我已经完成了关于由实部和虚部形成的两个虚数之和的代码。

#include<iostream> 
using namespace std; 

class Complex { 
private: 
    int real, imag; 
public: 
    Complex(int r, int i) {
        real = r; 
        imag = i;
    } 


    Complex operator + (Complex const &num1, Complex const &num2) { 
        Complex res; 
        res.real = num1.real + num2.real; 
        res.imag = num1.imag + num2.imag; 
        return res; 
    } 

    void print() { 
        cout << real << " + i" << imag << endl; 
    } 
}; 

int main() 
{ 
    Complex c1(10, 5), c2(2, 4); 
    Complex c3 = c1 + c2;
    c3.print(); 
} 

Run Code Online (Sandbox Code Playgroud)

有些东西应该是错误的,因为它显示了很多错误、注释和警告:(

error: ‘Complex Complex::operator+(const Complex&, const Complex&)’ must take either zero or one argument

error: no match for ‘operator+’ (operand types are ‘Complex’ and ‘Complex’)

note:   ‘Complex’ is not derived from ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>’
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 5

二进制(2参数)操作者不能是一个类的成员,它需要一个独立的函数,而不是:

class Complex {
...
public:
    ...
    friend Complex operator + (Complex const &lhs, Complex const &rhs);
    ...
};

Complex operator + (Complex const &lhs, Complex const &rhs) {
    return Complex(
        lhs.real + rhs.real,
        lhs.imag + rhs.imag
    );
}
Run Code Online (Sandbox Code Playgroud)

也可以内联:

class Complex {
...
public:
    ...
    friend Complex operator + (Complex const &lhs, Complex const &rhs) {
        return Complex(
            lhs.real + rhs.real,
            lhs.imag + rhs.imag
        );
    }
    ...
};
Run Code Online (Sandbox Code Playgroud)

所以,像这样的语句c1 + c2被处理为operator+(c1, c2).

一元(1个参数)运算符,在另一方面,必须是类构件作用于this作为左侧值:

class Complex {
...
public:
    ...
    Complex operator + (Complex const &rhs) const {
        return Complex(
            real + rhs.real,
            imag + rhs.imag
        );
    }
    ...
}; 
Run Code Online (Sandbox Code Playgroud)

然后像这样的语句c1 + c2被处理为c1.operator+(c2).