Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ less operator overload, which way to use?

Tags:

For example: in a C++ header file, if I defined a struct Record and I would like to use it for possible sorting so that I want to overload the less operator. Here are three ways I noticed in various code. I roughly noticed that: if I'm going to put Record into a std::set, map, priority_queue, … containers, the version 2 works (probably version 3 as well); if I'm going to save Record into a vector<Record> v and then call make_heap(v.begin(), v.end()) etc.. then only version 1 works.

  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;       } 

Basically, I would like to throw the questions here to see if someone could come up with some summary what's the differences among these three methods and what are the right places for each version?

like image 622
user268451 Avatar asked Nov 04 '11 23:11

user268451


People also ask

Which method is used to overload operators?

In Python, overloading is achieved by overriding the method which is specifically for that operator, in the user-defined class. For example, __add__(self, x) is a method reserved for overloading + operator, and __eq__(self, x) is for overloading == .

Which choice is a valid way to overload the ternary conditional operator?

It's not possible to overload the ternary operator.

Which operator is overloaded for C operation?

Input/Output Operators Overloading in C++ C++ is able to input and output the built-in data types using the stream extraction operator >> and the stream insertion operator <<. The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types like an object.

Which statement is best fit for operator overloading?

Which is the correct statement about operator overloading? Explanation: Both arithmetic and non-arithmetic operators can be overloaded. The precedence and associativity of operators remains the same after and before operator overloading.


1 Answers

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
like image 151
Pubby Avatar answered Sep 21 '22 14:09

Pubby