-
Overloading operator ==
Hi,
to practice overloading operators I'm building a Fractions class.
I have a question about comparison operators. In a tutorial, the overloaded == returned an int (1 or 0) - wouldn't it make more sense to return a bool (true or false)? Would it matter - I guess overloading these operators is important if you want to use the sort algorithm on them and such?
This is what I have to compare fractions. Is it OK?
Code:
class Fraction
{
public:
Fraction(int up = 0, int low = 1):upper(up), lower(low) {}
~Fraction() {}
//....
bool operator== (const Fraction f)
{
if (this->upper * f.lower == this->lower*f.upper)
return true;
else
return false;
}
private:
int upper, lower;
};
-
The only thing I have to say, is pass a const reference to Fraction f, so that you don't have to copy Fraction f everytime you use operator ==().
-
Code:
if (this->upper * f.lower == this->lower*f.upper)
return true;
else
return false;
Just a nit, but this can be simplified a bit to this:
Code:
return this->upper * f.lower == this->lower * f.upper;
-
Thanks, both are excellent suggestions! Never thought of that...
-
>> wouldn't it make more sense to return a bool (true or false)?
Yes. You should return a bool.
>> This is what I have to compare fractions. Is it OK?
If you make it a member function, you should make the function const as well as making the parameter a const reference as citizen mentioned. However, in this case it should not be a member. It should be a non-member function:
Code:
bool operator==(const Fraction& f1, const Fraction& f2);
You would have to make it a friend in this case, since you use the private upper and lower members, but that is ok.