【问题标题】:How to overload operator + with the parameters of a class? [duplicate]如何用类的参数重载运算符+? [复制]
【发布时间】:2020-05-24 18:08:53
【问题描述】:

我正在学习 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(); 
} 

应该有问题,因为它显示了很多错误、注释和警告:(

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>’

【问题讨论】:

  • 好的,有哪些错误、注释和警告?
  • 你已经像朋友函数一样重载了它们。
  • 你在res.imag = num1.imag + num1.imag;中有一个双重num1.imag
  • 注意:C++ 已经有std::complex

标签: c++ class oop object operator-overloading


【解决方案1】:

二进制(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
    );
}

也可以内联:

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

因此,像c1 + c2 这样的语句会被处理为operator+(c1, c2)

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

class Complex {
...
public:
    ...
    Complex operator + (Complex const &rhs) const {
        return Complex(
            real + rhs.real,
            imag + rhs.imag
        );
    }
    ...
}; 

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

【讨论】:

    【解决方案2】:

    您定义operator+ 的方式很好,期望它需要是friend 函数。另外,请注意Complex res; 不会编译,因为您没有默认构造函数。

    你可以这样定义函数:

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

    这是demo

    另请注意,我修复了您将 num1 的虚部添加两次的错误。

    【讨论】:

    • 感谢您告知num1 被写了两次,因为我没有注意到。 :)
    猜你喜欢
    • 2015-08-22
    • 1970-01-01
    • 2010-10-21
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2012-03-14
    • 1970-01-01
    相关资源
    最近更新 更多