2012-04-19 96 views
4

我有一個<運算符重載的問題。 我有這個類:C++運算符<overloading

WordEntry.h:

class WordEntry 
{ 
public: 
    WordEntry(string word); 
    ~WordEntry(); 

    bool operator<(const WordEntry otherWordEntry); 

    string getWord(); 

private: 
    string _word; 
}; 

WordEntry.cpp(我刪除構造&析構函數):

string WordEntry::getWord() 
{ 
    return _word; 
} 


bool WordEntry::operator<(WordEntry otherWordEntry) 
{ 
    return lexicographical_compare(_word.begin(),_word.end(),otherWordEntry.getWord().begin(),otherWordEntry.getWord().end()); 
} 

一切都很好,當我在主要使用它.cpp那樣:

WordEntry w1("Der"); 
    WordEntry w2("das"); 

    if (w1.operator<(w2)) { 
     cout << "w1 > w2"; 
    } 
    else 
    { 
     cout << "w2 > w1"; 
    } 

但是當我打電話給sort()vectorWordEntry對象,我會得到錯誤信息

無效操作數的二進制表示( '常量WordEntry' 和 '常量 WordEntry')

並將其指向​​。

有沒有人知道這裏發生了什麼?

+0

'const'複製幾乎失敗的目的... – AJG85 2012-04-19 18:43:53

回答

7

現在<的參數是const,但成員不是。這意味着一個<之間的對比將會失敗,因爲它不能綁定到<。你需要讓會員和參數都const

bool operator<(const WordEntry& otherWordEntry) const; 

bool WordEntry::operator<(const WordEntry& otherWordEntry) const { 
    ... 
} 

注:由於在評論中指出,你也應該參考

+2

通過引用傳遞也是一個好主意。 – juanchopanza 2012-04-19 18:46:24

+0

@juanchopanza好點,已更新 – JaredPar 2012-04-19 18:49:03

+0

就是這樣,謝謝 – LeonS 2012-04-19 18:51:05

2

使用右值const引用傳遞WordEntry,使方法常量來保證編譯器不會改變對象。

bool operator<(const WordEntry& otherWordEntry) const 
{ 
    // comparison 
} 

您也不需要顯式調用操作符。 曾經爲WordEntry對象,你可以做到這一點定義:既然你不使用自定義的比較謂詞你可以只使用

if (w1 < w2) { // etc } 

std::string::operator<

return _word < otherWordEntry._word; 

大衛使得在返回一個很好的點內部成員的價值。如果你想使用lexicographical_compare與訪問者,而不是_word成員直接(它可以如你在類範圍內是),那麼你應該定義它像這樣:

const string& getWord() const { return _word; } 
2
string WordEntry::getWord() 
bool WordEntry::operator<(WordEntry otherWordEntry) 
{ 
    return lexicographical_compare(_word.begin(), 
            _word.end(), 
            otherWordEntry.getWord().begin(), 
            otherWordEntry.getWord().end()); 
} 

getWord成員函數創建內部成員屬性的副本並返回副本。連續兩次調用getWord將返回具有相同內容的兩個不同std::string實例,但它們是不同的對象。 lexicographical_compare函數要求第一個和第二個參數是迭代器到同一個容器,類似的第三個和第四個參數。在你的情況下,你正在傳遞迭代器到不同的容器(字符串),它將在函數內部進行比較,並會產生未定義的行爲。

最簡單的解決方案是具有getWord返回一個const參照內部std::string,以這種方式,迭代器將都是指在右手側對象的內部對象。

正如其他人也提到,你應該通過WordEntry通過const參考,並operator<const,以提高的代碼。但是在你的實現中的問題是來自不同容器的迭代器的混合。