How to output a multiplied user-created C ++ class

I am working on assigning operator overloading to a user-created class of rational numbers, but cannot output two Rational objects on the same line. For instance:

std::cout<<5*10<<std::endl; 

Outputs 50 are excellent. However, when I try to do

 std::cout<<Rational_1*Rational_2<<std::endl; 

I get an error message. If I instead assign a value to the third rational, for example

 Rational_3=Rational_1*Rational_2; std::cout<<Rational_3<<std::endl; 

Then the program will come out just fine. I brought this to my professor, but even he does not know how to fix it. Any explanation of why this is happening would be helpful. I would like to know why this is a problem and not just getting a piece of code that works.

 #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; } } } 
+5
source share
2 answers

The difference between operator<< , which takes an int , as in your first fragment, is that it takes an argument by value.

Your overloaded operator<< takes a Rational object by reference and Rational_1*Rational_2 returns a temporary object, temporary objects cannot communicate with non-constant links.

Either take your argument by value, or const& to fix this:

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

or

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

Declare an operator as

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

You cannot bind a temporary object to a constant lvalue reference.

+2
source

Source: https://habr.com/ru/post/1275652/


All Articles