Reputation: 445
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?
Upvotes: 11
Views: 32289
Reputation: 11
friend bool operator==( Rationalnumber l, Rationalnumber r );
when you declare it as non-member function, it can take two arguments. when you declare it as member function, it can only take one argument.
Upvotes: 1
Reputation: 227578
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;}
Upvotes: 22
Reputation: 131
As a member operator overload it should only take one argument, the other being this
.
class Foo
{
int a;
public:
bool operator==(const Foo & foo);
};
//...
bool Foo::operator==(const Foo & foo)
{
return a == foo.a;
}
Upvotes: 4
Reputation: 133
You should remove your operator== from a RationalNumber to somewhere else. As it is declared inside a class it is considered that 'this' is the first argument. From semantics it is seen that you offer 3 arguments to a compiler.
Upvotes: 2