c++ - 没有运算符“=”与这些操作数匹配。我已经超载了它,但它似乎不能正常工作
问题描述
我已经重载了“=”运算符来接受我的理性类的对象,但它似乎不起作用。这是我的标题和我的类定义
#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 引用参数,并尝试通过为其分配“数字”对象来对其进行修改。
如果你想修改'r',你应该声明'r'作为参考如下。
istream& operator>>(istream& is, rational& r)
推荐阅读
- sql - 检索 Quantite 依赖于 SQL 类型
- rest - AS400 RPGLE 无法使用 SSL 使用 REST API
- haskell - 找到最大的 n 使得 n! < k 在 Haskell 中,使用 foldl 和无限级数
- css - 我如何在引导程序 4 中为响应式切换菜单设置自定义断点
- javascript - 不是下载,而是在浏览器中打开文件
- sql - oracle 索引中的并行度影响数据库负载
- sql - 连接包含逗号分隔值的表
- java - 访问字符串数组时获取 ArrayIndexOutOfBoundException
- javascript - 单击时显示/隐藏元素
- ruby-on-rails - Ubuntu 安装了 ruby-dev 但仍然无法安装 gem nokogiri