c++ 少运算符重载,使用哪种方式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8016880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:51:49  来源:igfitidea点击:

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

c++stloperator-overloading

提问by user268451

For example: in a C++ header file, if I defined a struct Recordand 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 Recordinto a std::set, map, priority_queue, … containers, the version 2 works (probably version 3 as well); if I'm going to save Recordinto a vector<Record> vand then call make_heap(v.begin(), v.end())etc.. then only version 1 works.

例如:在 C++ 头文件中,如果我定义了 astruct Record并且我想使用它进行可能的排序,以便我想重载less operator. 以下是我在各种代码中注意到的三种方式。我粗略地注意到:如果我要放入Record一个std::set, map, priority_queue, ... 容器,版本 2 可以工作(可能版本 3 也是如此);如果我要保存Record到一个vector<Record> v然后调用make_heap(v.begin(), v.end())等等。那么只有版本 1 有效。

  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?

基本上,我想在这里抛出问题,看看是否有人可以提出一些总结这三种方法之间的区别以及每个版本的正确位置是什么?

采纳答案by Pubby

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. lhsdoes not have to be a Record
  1. 它不一定是friend.
  2. lhs不必是 Record

回答by Zvonimir

The best way to define the less operator is:

定义 less 运算符的最佳方法是:

struct Record{
    (...)
    const bool operator < ( const Record &r ) const{
        return ( num < r.num );
    }
};

回答by Joshua

Favor in-class unless it cannot be in-class because first argument is the wrong type.

支持课堂教学,除非它不能在课堂教学,因为第一个参数是错误的类型。