【问题标题】:Compilation error on operator overloading when sorting vector对向量进行排序时运算符重载的编译错误
【发布时间】:2012-06-03 12:15:32
【问题描述】:

我有一个大致定义如下的类。其中,它有一个< 比较运算符。

class DictionarySearchItem {

public:

    DictionarySearchItem(); 
    double relevance() const;
    bool operator<(const DictionarySearchItem& item) { return relevance() > item.relevance(); }

};

typedef std::vector<DictionarySearchItem> DictionarySearchItemVector;

然后我以这种方式使用该类:

DictionarySearchItemVector searchItems;

for (unsigned i = 0; i < entries.size(); i++) {
    // ...
    // ...
    DictionarySearchItem item;
    searchItems.push_back(item);
}

但是,当我尝试对向量进行排序时:

std::sort(searchItems.begin(), searchItems.end());

我在使用 MinGW 时遇到以下编译错误。

/usr/include/c++/4.2.1/bits/stl_algo.h:91: erreur : passing 'const hanzi::DictionarySearchItem' as 'this' argument of 'bool hanzi::DictionarySearchItem::operator<(const hanzi::DictionarySearchItem&)' discards qualifiers

我不太明白我的代码有什么问题,而且我也不清楚错误消息。相同的代码在 MSVC2008 上编译得很好。知道可能是什么问题吗?

【问题讨论】:

  • 我第一次得到了这个错误的解释。我已经更新了我的答案。我希望现在更清楚了。

标签: c++ compiler-errors g++ operator-overloading mingw


【解决方案1】:

您需要将小于号运算符设为const:

bool operator<(const DictionarySearchItem& item) const { ... }
                                                   ^

原因可能是sort 依赖于这样一个事实,即被比较的元素不会因比较而改变。这可以通过将&lt; 比较的两边都设置为 const 来强制执行,这意味着运算符必须是 const,以及它的参数。

【讨论】:

  • 我没有得到解释。我们不应该能够毫无问题地从非常量方法调用 const 方法吗?
  • @Hippo 是的,当然可以。糟糕,我今天睡着了。
  • @Hippo 好吧,这意味着排序算法在 &lt; 比较的 LHS 上传递了一个 const DictionarySearchItem,这要求运算符是 const (它处理 RHS 的 constness 是因为运算符的参数是const &amp;)。逻辑是排序不能处理比​​较时元素的变化,因为这会完全破坏排序逻辑。所以&lt; 的两边都必须是 const (我认为这在标准中没有明确说明)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多