c++stloperator-overloading

"less" operator overload, which way to use?


In a header file I defined a struct Record. I would like to use it for possible sorting so I want to overload the less operator. Here are three ways I noticed in various code. I roughly noticed that:

struct Record
{
    char c;
    int num;
    
    //version 1
    bool operator <(const Record& rhs)
    {
       return this->num>rhs.num;
    }
    
    //version 2
    friend bool operator <(const Record& lhs, const Record& rhs) //friend claim has to be here
    {
       return lhs->num>rhs->num;
    }
};

In the same header file for example:

//version 3
inline bool operator <(const Record& lhs, const Record& rhs)
{
   return lhs->num>rhs->num;
}

What's the differences among these three methods and what are the right places for each version?


Solution

  • They are essentially the same, other than the first being non-const and allowing you to modify itself.

    I prefer the second for 2 reasons:

    1. It doesn't have to be a friend.
    2. lhs does not have to be a Record