【问题标题】:No operator "=" matches these operands. I have overloaded it but it doesn't seem to be working properly没有运算符“=”与这些操作数匹配。我已经超载了它,但它似乎不能正常工作
【发布时间】:2020-01-16 15:27:57
【问题描述】:

我已经重载了“=”运算符来接受我的理性类的对象,但它似乎不起作用。这是我的标题和我的类定义

#include <iostream>
#include <assert.h>
#include <fstream>
using namespace std;

class rational {
public:

rational();
rational(int numerator, int denominator);
rational(const rational& r);

int numerator() const;
int denominator() const;

const rational& operator = (const rational& rhs);  //this is what I'm having issues with

private:

int myNumerator, myDenominator;

void reduce();
};

这是我的重载实现(主要在下面):

const rational& rational::operator = (const rational& rhs) {
if (*this != rhs) { //added asterisk, otherwise operator would not work
    myNumerator = rhs.numerator();
    myDenominator = rhs.denominator();
}
return *this;
}

在下面的实现中,我遇到了使用“=”运算符的问题:

istream& operator>>(istream& is, const rational& r) {
    char divisionSymbol;
    int numerator = 0, denominator = 0;

    is >> numerator >> divisionSymbol >> denominator;
    assert(divisionSymbol == '/');
    assert(denominator != 0);
    rational number(numerator, denominator);
    r = number; /* Error: no operator matches these operands (more specifically no operator found
 which takes a left-hand operand of type 'const rational') but I am unsure how to fix that as the
 assignment operator only takes one parameter (unless I am mistaken)*/
    return is;
}

我一辈子都想不出什么是行不通的,可能是语法问题?我的教授非常老派,所以可能是过时的做法?任何提示将不胜感激。

【问题讨论】:

  • 您将r 声明为const &amp;。如果要修改,请删除const
  • 谢谢!不敢相信我没有注意到,非常感谢
  • 你几乎不应该重载 operator=。当然不适合像你这样的简单课程。

标签: c++ class operator-overloading assignment-operator


【解决方案1】:

问题不在于 '=' 运算符重载函数。问题在于“>>”运算符重载函数。您将 r 声明为 const 引用参数,并尝试通过为其分配“数字”对象来修改它。

如果你想修改'r',你应该声明'r'作为参考,如下所示。

istream& operator>>(istream& is, rational& r)

【讨论】:

    猜你喜欢
    • 2018-06-02
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多