Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading operator== complaining of 'must take exactly one argument'

Tags:

c++

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?

like image 768
chlong Avatar asked Jun 27 '12 14:06

chlong


People also ask

Can == be overloaded?

Overloadable operators The true and false operators must be overloaded together. Must be overloaded in pairs as follows: == and !=

Can we overload == operator in C ++?

The overloaded operator must have at least one operands of the user-defined types. You cannot overload an operator working on fundamental types.

Which operator does not take any argument if overloaded?

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 .

What are the rules of overloading operator?

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 “()”.


1 Answers

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;}
like image 184
juanchopanza Avatar answered Jan 02 '23 21:01

juanchopanza