1

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.

Community
  • 1
  • 1
frostmatthew
  • 3,260
  • 4
  • 40
  • 50
  • 1
    Just a note, since the function is a friend function it should be able to take the private members so the getters are unnecessary unless I'm not seeing something. – Rapptz Aug 19 '12 at 20:51

1 Answers1

2

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.

Vlad
  • 35,022
  • 6
  • 77
  • 199
  • Thanks, your second suggestion gave errors regarding discarding qualifiers but the third option seems to work great (and it seems all I needed to do was remove the `inline` modifier and the `Tweet::` from my original code) – frostmatthew Aug 19 '12 at 21:06
  • 1
    @Exupery: you're welcome! Well, for the 2nd suggestion to work, perhaps you need `getID` to be a `const` function. – Vlad Aug 19 '12 at 23:12