我已经创建了一个Rational类,并且仅对Rational vs Rational进行了重载==运算符,而不是Rational vs int比较,但它在某种程度上也适用于后一种情况。它为什么有效?这是代码:
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”返回true而“r == 3”为false,但“== operator”仅为类与类比较重载... 这是所有的代码:
#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;
}