gpt4 book ai didi

c++ - 如何输出乘以用户创建的类c++

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:22:56 25 4
gpt4 key购买 nike

我正在为用户创建的有理数类处理赋值重载运算符,但无法在同一行中输出两个“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返回一个临时对象,临时对象不允许绑定(bind)到非常量引用。

按值或 const& 接受你的论点解决这个问题:

friend ostream& operator <<(ostream& out, const Rational& output);

或者

friend ostream& operator <<(ostream& out, Rational output);

关于c++ - 如何输出乘以用户创建的类c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49055144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com