排序向量时运算符重载的编译错误

lau*_*ent 3 c++ mingw compiler-errors g++ operator-overloading

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

class DictionarySearchItem {

public:

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

};

typedef std::vector<DictionarySearchItem> DictionarySearchItemVector;
Run Code Online (Sandbox Code Playgroud)

然后我用这种方式使用这个类:

DictionarySearchItemVector searchItems;

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

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

std::sort(searchItems.begin(), searchItems.end());
Run Code Online (Sandbox Code Playgroud)

我在使用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
Run Code Online (Sandbox Code Playgroud)

我不太明白我的代码有什么不对,错误信息对我来说并不清楚.使用MSVC2008编译相同的代码.知道可能是什么问题吗?

jua*_*nza 5

您需要创建less-than运算符const:

bool operator<(const DictionarySearchItem& item) const { ... }
                                                   ^
Run Code Online (Sandbox Code Playgroud)

原因可能是这sort依赖于被比较的元素不能因比较而改变的事实.这可以通过使<比较的两边都是const 来强制执行,这意味着操作符必须是const,以及它的参数.