Apart from that, I hope you do have a default constructor Rational::Rational() which initializes numerator and denominator to sane values. Garbage values are sometimes a sign of forgotten initialization.
Finally... it is good practice to overload operator+ and family externally to the class.
This is because by having them as members you force the first parameter to be an object of your class. This matters when you want to add other things than Rational to your object.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class Rational
{
// ...
public:
Rational operator + (int i) const
{
// ..
}
};
int main()
{
Rational r;
Rational result1 = r + 1; // works
Rational result2 = 1 + r; // doesn't work
}
yes i did do them in the class header file and i do have the default constructor, but for the sake of ease i did not post the entire code because the problem is with the operator overloading not anything else.
and when i tried that code instead of it giving me what i want, it gives me a weird number -858993460 for addition of the 2 fractions for example when i did 3/8 + 1/6 it gave me -858993460/-858993460
#include <iostream>
struct rational
{
explicit rational( int n = 0, int d = 1 ) : num(n), den(d) {}
rational& operator+= ( const rational& other )
{
num = num * other.den + other.num * den ;
den *= other.den ;
return *this ;
}
rational& operator+= ( int v )
{
num = num + v * den ;
return *this ;
}
int numerator() const { return num ; }
int denomiator() const { return den ; }
private:
int num ;
int den ;
};
// operator+ is implemented in terms of +=
// note: a is passed by value
rational operator+ ( rational a, const rational& b ) { return a += b ; }
// note: r is passed by value
rational operator+ ( rational r, int i ) { return r += i ; }
rational operator+ ( int i, rational r ) { return r += i ; }
std::ostream& operator<< ( std::ostream& stm, const rational& r )
{ return stm << '(' << r.numerator() << '/' << r.denomiator() << ')' ; }
int main()
{
std::cout << rational{3,2} + rational{1,3} << '\n'
<< rational{3,5} + 2 << '\n'
<< 7 + rational{5,9} << '\n' ;
}