c ++减少运算符过载,这种方式使用? [英] c++ less operator overload, which way to use?

查看:168
本文介绍了c ++减少运算符过载,这种方式使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:在C ++头文件中,如果我定义了一个 struct Record ,我想使用它进行可能的排序,以便我重载 less运算符。这里有三种方式我注意到在各种代码。我大致注意到:如果我要把记录放入 std :: set map priority_queue ,...容器,版本2工程如果我要将记录保存到向量< Record> v 然后调用 make_heap(v.begin(),v.end())等..然后只有版本1工作。 >

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

在同一个头文件中:

      //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?

推荐答案

这些方法本质上是

我喜欢第二个因为两个原因:

I prefer the second for 2 reasons:


  1. 不必是朋友

  2. lhs 不一定是记录

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

这篇关于c ++减少运算符过载,这种方式使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆