【问题标题】:Overloading gives me error: no match for ‘operator<’重载给了我错误:'operator<' 不匹配
【发布时间】:2018-05-15 15:05:00
【问题描述】:

在代码中,我有Events 的队列,按waitTime 排序。我想找出当前应该执行哪个Events,所以我这样做:

std::vector<Event>::iterator up = std::upper_bound(queue.begin(), queue.end(), currentTime);

如果我重载 &lt; 运算符,std::upper_bound 将起作用:

bool Event::operator<(const double& currentTime) const
{
    return waitTime < currentTime;
}

但我有一个错误:

   error: no match for ‘operator<’ (operand types are ‘const double’ and ‘Event’)

我应该如何正确地重载'operator

附言

class Event{
public:
    double startTime;
    double waitTime;
    double size;

    Event(double start, double wait, double size);
    bool operator<(const Event& otherEvent) const;
    bool operator<(const double& currentTime) const;
    bool operator() (const Event & event, const double & right);
};

【问题讨论】:

  • 什么是 endTime?
  • Event 被定义为...?
  • 请发minimal reproducible example,不要乱码。
  • 顺便说一句,您使用&lt;= 来实现&lt; 看起来非常可疑,通常这两个强加完全不同的顺序
  • 请注意,一旦你得到这个编译,还有一个严重的问题:waitTime &lt;= currentTime 不是严格的弱排序,所以代码的行为是未定义的。问题是当waitTime 等于currentTime 时,operator&lt; 报告 both waitTime 出现在 currentTime 之前 并且 currentTime 出现在waitTime之前。

标签: c++ c++11 vector casting operator-overloading


【解决方案1】:

这可能真的很有用。 以下链接涉及全局运算符覆盖及其限制,以及 C++ 11 中 friend 关键字的使用。

[链接]Why should I overload a C++ operator as a global function (STL does) and what are the caveats?

【讨论】:

    【解决方案2】:

    考虑到这个错误信息

    error: no match for ‘operator

    你需要声明运营商

    bool operator<(const double &, const Event &);
    

    似乎在算法中使用了条件

    currentTime < *it
    

    另一种方法是将算法称为

    std::vector<Event>::iterator up = std::upper_bound(queue.begin(), 
                                                       queue.end(), 
                                                       Event { 0.0, currentTime, 0.0 });
    

    即通过将currentTime 强制转换为Event 类型的对象,因为Event 类型的对象已经有重载的运算符<..>

    bool operator<(const Event& otherEvent) const;
    

    【讨论】:

      【解决方案3】:
      bool Event::operator<(const double& currentTime) const
      

      只为以下情况定义小于运算符

      Event e;
      //...
      double d = /*...*/;
      bool result = e < d;
      

      以下情况

      bool result = d < e;
      

      定义这些运算符时,您必须同时定义它们!理想情况下将它们都定义为非成员函数

      bool operator<(const Event& e, const double& currentTime);
      bool operator<(const double& currentTime, const Event& e);
      

      (为什么是非成员函数?致improve encapsulation

      John Lakos 有一个has a wonderful CPPcon talk,他就是这么说的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-06
        • 2014-07-03
        • 2011-12-10
        • 2013-07-31
        • 1970-01-01
        • 2011-02-06
        • 2019-03-18
        • 1970-01-01
        相关资源
        最近更新 更多