I am trying to overload the operator==
, but the compiler is throwing the following error:
‘bool Rationalnumber::operator==(Rationalnumber, Rationalnumber)’ must take exactly one argument
My short piece of code is as follows:
bool Rationalnumber::operator==(Rationalnumber l, Rationalnumber r) {
return l.numerator() * r.denominator() == l.denominator() * r.numerator();
}
Declaration:
bool operator==( Rationalnumber l, Rationalnumber r );
Does anyone have any ideas why it's throwing the error?
Overloadable operators The true and false operators must be overloaded together. Must be overloaded in pairs as follows: == and !=
The overloaded operator must have at least one operands of the user-defined types. You cannot overload an operator working on fundamental types.
Most can be overloaded. The only C operators that can't be are . and ?: (and sizeof , which is technically an operator). C++ adds a few of its own operators, most of which can be overloaded except :: and .
Rules for operator overloading in C++Only built-in operators can be overloaded. If some operators are not present in C++, we cannot overload them. The precedence of the operators remains same. The overloaded operator cannot hold the default parameters except function call operator “()”.
If operator==
is a non static data member, is should take only one parameter, as the comparison will be to the implicit this
parameter:
class Foo {
bool operator==(const Foo& rhs) const { return true;}
};
If you want to use a free operator (i.e. not a member of a class), then you can specify two arguments:
class Bar { };
bool operator==(const Bar& lhs, const Bar& rhs) { return true;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With