没有运算符“ =”与这些操作数匹配。我已经超载了,但似乎无法正常工作

时间:2019-09-15 16:10:21

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

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

#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();
};

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

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;
}

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

1 个答案:

答案 0 :(得分:0)

问题不具有'='运算符重载功能。问题在于“ >>”运算符重载功能。您已将r声明为const参考参数,并试图通过为其分配'number'对象来对其进行修改。

如果要修改'r',则应将'r'声明为以下引用。

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