I wanted to add two rational numbers and display them in the form of p/q using overloading the operators + and <<.
I'm using friend function, because the function for addition and display are taking multiple and different types of parameters. Inside the addition function I'm performing a normal addition of fractions, like how we do in real life. But when i run the code i get an error that can't convert Rational to Rational(),
Error: Rational.cpp: In function 'int main()': Rational.cpp:51:15: error: assignment of function 'Rational R3()' R3 = R1 + R2; Rational.cpp:51:15: error: cannot convert 'Rational' to 'Rational()' in assignment*
i have no idea why it's saying that .... ??
C++
#include <iostream>
using namespace std;
class Rational
{
private:
int P;
int Q;
public:
Rational(int p = 1, int q = 1)
{
P = p;
Q = q;
}
friend Rational operator+(Rational r1, Rational r2);
friend ostream & operator<<(ostream &out, Rational r3);
};
Rational operator+(Rational r1, Rational r2)
{
Rational temp;
if(r1.Q == r2.Q)
{
temp.P = r1.P + r2.P;
temp.Q = r1.Q;
}
else
{
temp.P = ((r1.P) * (r2.Q)) + ((r2.P) * (r1.Q));
temp.Q = (r1.Q) * (r2.Q);
}
return temp;
}
ostream & operator<<(ostream &out, Rational r3)
{
out<<r3.P<<"/"<<r3.Q<<endl;
return out;
}
int main()
{
Rational R1(3,4);
Rational R2(5,6);
Rational R3();
R3 = R1 + R2;
cout<<R3;
}
This
Rational R3();
declares a function called R3
that returns a Rational
and takes no parameters. It does not define R3
to be a default constructed Rational
. Change the line to any of the below
Rational R3;
Rational R3{};
auto R3 = Rational();
auto R3 = Rational{};