Reputation: 3298
I'm fairly new to C++ and attempting to overload the < operator in a class.
In my header file I have:
friend bool operator<(const Tweet& a, const Tweet& b);
and in the class file I have:
inline bool Tweet::operator<(const Tweet& a, const Tweet& b) {
return (a.getID() < b.getID());
}
Currently I'm getting an error ‘bool Tweet::operator<(const Tweet&, const Tweet&)’ must take exactly one argument
Removing the Tweet::
changes the error to an undefined reference and removing the second argument changes the error to "must take exactly two arguments"
PS - I've tried following the appropriate section in Operator overloading as well as a few related questions but then I just get a variety of different errors.
Upvotes: 1
Views: 4167
Reputation: 35584
Well, you are declaring a free-standing function to be a friend, and then define a class member function as comparison. That is not exactly right.
If you define the comparison operator having two arguments, you have to declare it static:
static bool Tweet::operator<(const Tweet& a, const Tweet& b) {
return (a.getID() < b.getID());
}
This way a < b
gets interpreted as Tweet::operator<(a, b);
.
Without static
, you get implicitly 3 arguments: *this
, a
and b
.
Alternately, you can define an instance operator, taking one argument and comparing it to the current instance:
bool Tweet::operator<(const Tweet& b) {
return (getID() < b.getID());
}
This way a < b
gets interpreted as a.operator<(b);
.
Alternately, you can define a free-standing function (this is where you actually might need friend
):
bool operator<(const Tweet& a, const Tweet& b) {
return (a.getID() < b.getID());
}
This way a < b
gets interpreted as operator<(a, b);
.
Either way is good.
Upvotes: 2