2012-06-03 52 views
3

我有一個粗略定義類如下。其中,它有一個<比較運算符。排序向量時,運算符重載編譯錯誤

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編譯。任何想法可能是什麼問題?

+0

我第一次得到了這個錯誤的解釋。我已經更新了我的答案。我希望現在更清楚。 – juanchopanza

回答

5

你需要使低於運營商const

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

的原因可能是sort依賴於事實,被比較的元素不能改變作爲比較的結果。這可以通過將<比較的兩端都設爲const來強制執行,這意味着運算符必須是const,以及它的參數。

+0

我沒有得到解釋。我們不應該能夠毫無問題地從非const方法調用const方法嗎? – AbdullahC

+0

@Hippo是的,當然可以。我的不好,我今天半睡着了。 – juanchopanza

+0

OK..cool。那麼,真正的解釋是什麼? :) – AbdullahC