我正在为一个用户创建的有理数类重写一个赋值重载操作符,但不能在同一行中输出两个“Rational”对象。例如:
std::cout<<5*10<<std::endl;
输出50就好了。但是,当我尝试做的时候,
std::cout<<Rational_1*Rational_2<<std::endl;
我收到一个错误。如果我改为将值赋给第三个理性,例如
Rational_3=Rational_1*Rational_2;
std::cout<<Rational_3<<std::endl;
然后程序输出就好了。我把它带到了我的教授那里,但即使他不知道如何解决它。关于为什么会发生这种情况的任何解释都会有所帮助。我想知道为什么这是一个问题,而不仅仅是简单地获得一段有用的代码。
#include <iostream>
using namespace std;
class Rational{
public:
Rational();
Rational(int whole_number);
Rational(int numerator_input,int denominator_input);
friend Rational operator *(Rational rat_1, Rational rat_2);
` friend ostream& operator <<(ostream& out,Rational& output);
void simplify();
private:
int numerator,denominator;
};
int main(){
Rational r1(2,3),r2(3,4),r3;
r3=r1*r2;
cout<<r3<<endl;
//cout<<r1*r2<<endl;
return 0;
}
Rational::Rational(){
numerator=0;
denominator=1;
}
Rational::Rational(int whole_number){
numerator=whole_number;
denominator=1;
}
Rational::Rational(int numerator_input,int denominator_input){
numerator=numerator_input;
if(denominator_input==0){
cout<<"A rational number can not have a 0 in the denominator\n";
exit (5);
}
denominator=denominator_input;
simplify();
}
ostream& operator <<(ostream& out,Rational& output){
out<<output.numerator<<"/"<<output.denominator;
return out;
}
Rational operator *(Rational rat_1, Rational rat_2){
Rational rat_3;
rat_1.simplify();
rat_2.simplify();
rat_3.numerator=rat_1.numerator*rat_2.numerator;
rat_3.denominator=rat_1.denominator*rat_2.denominator;
rat_3.simplify();
return rat_3;
}
void Rational::simplify(){
//Flip negative sign to numerator
for(int counter=1000000;counter>0;counter--){
if((numerator%counter==0)&&(denominator%counter==0))
{
numerator=numerator/counter;
denominator=denominator/counter;
}
}
}
采用operator<<
的int
与你的第一个片段之间的区别在于它是按值进行的。
您的重载operator<<
通过引用获取Rational
对象,Rational_1*Rational_2
返回临时对象,不允许临时对象绑定到非const引用。
要么通过值或const&
来解决这个问题:
friend ostream& operator <<(ostream& out, const Rational& output);
要么
friend ostream& operator <<(ostream& out, Rational output);
声明运算符就像
friend ostream& operator <<(ostream& out, const Rational& output);
^^^^^
您不能将临时对象绑定到非常量左值引用。