C++ “无操作员”=&引用;匹配这些操作数。我让它超载了,但它没有';他似乎工作不正常
我重载了“=”操作符以接受我的类rational的对象,但它似乎不起作用。这是我的标题和我的类定义C++ “无操作员”=&引用;匹配这些操作数。我让它超载了,但它没有';他似乎工作不正常,c++,class,operator-overloading,assignment-operator,C++,Class,Operator Overloading,Assignment Operator,我重载了“=”操作符以接受我的类rational的对象,但它似乎不起作用。这是我的标题和我的类定义 #include <iostream> #include <assert.h> #include <fstream> using namespace std; class rational { public: rational(); rational(int numerator, int denominator); rational(const ration
#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();
};
下面是我在以下实现中使用“=”运算符时遇到的问题:
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声明为常量引用参数,并试图通过向其分配“number”对象来修改它 如果您想修改“r”,您应该声明“r”作为引用,如下所示
istream& operator>>(istream& is, rational& r)
您正在将
r
声明为const&
。如果要修改,请删除常量
谢谢!真不敢相信我没有注意到这一点,非常感谢您几乎永远不应该重载运算符=。当然不是像你这样的简单类。
istream& operator>>(istream& is, rational& r)