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.
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:
This way
a < bgets interpreted asTweet::operator<(a, b);.Without
static, you get implicitly 3 arguments:*this,aandb.Alternately, you can define an instance operator, taking one argument and comparing it to the current instance:
This way
a < bgets interpreted asa.operator<(b);.Alternately, you can define a free-standing function (this is where you actually might need
friend):This way
a < bgets interpreted asoperator<(a, b);.Either way is good.