I have created a Rational class and have overloaded == operator for only Rational vs Rational comparison, not Rational vs int comparison yet somehow it is working for latter case as well. Why is it working? Here's the code:
bool Rational::operator==(const Rational& r) const
{
if(denominator == r.getDenominator())
if(numerator == r.getNumerator())
return true;
else
return false;
}
int main()
{
Rational r(16, 8); // 16/8
cout << boolalpha << (r == 3) << '\n'; //false
cout << boolalpha << (r == 2) << '\n'; //Why this returns "true" without knowing how to compare Rational with int?!
return 0;
}
"r == 2" is returning true and "r == 3" false, yet "== operator" is overloaded for class vs class comparison only... here's all of the code:
#include <iostream>
#include <cstdlib>
using namespace std;
class Rational {
public:
Rational( int nume, int denom );
Rational( int nume );
void setNumeDenom( int nume, int denom );
bool operator==( const Rational& r ) const;
int getNumerator() const { return numerator; }
int getDenominator() const { return denominator; }
private:
int numerator;
int denominator;
};
int greatestCommonDivisor( int a, int b )
{
if( b == 0 )
return a;
return greatestCommonDivisor(b, a % b);
}
Rational::Rational( int n, int d )
{
setNumeDenom( n, d );
}
Rational::Rational( int n )
{
setNumeDenom( n, 1 );
}
void Rational::setNumeDenom( int n, int d )
{
int gcd = greatestCommonDivisor(n ,d);
if( d != 0 && gcd > 0 )
{
numerator = n / gcd;
denominator = d / gcd;
}
else
{
cout << "denominator cannot be Zero.\n";
abort();
}
}
bool Rational::operator==(const Rational& r) const
{
if(denominator == r.getDenominator())
if(numerator == r.getNumerator())
return true;
else
return false;
}
int main()
{
Rational r(16, 8);
cout << boolalpha << (r == 2) << '\n'; //true
cout << boolalpha << (r == 3) << '\n'; //false
return 0;
}