2013-05-13 49 views
0

我對hash_map做了一些測試,使用struct作爲鍵。我定義的結構:爲什麼運營商<被定義爲非會員?

struct ST 
{ 

    bool operator<(const ST &rfs) 
    { 
     return this->sk < rfs.sk; 
    } 

    int sk; 
}; 

和:

size_t hash_value(const ST& _Keyval) 
{ // hash _Keyval to size_t value one-to-one 
    return ((size_t)_Keyval.sk^_HASH_SEED); 
} 

則:

stdext::hash_map<ST, int> map; 
ST st; 
map.insert(std::make_pair<ST, int>(st, 3)); 

它給了我一個編譯器錯誤:二進制 '<':沒有操作員發現這需要左手'const ST'類型的操作數(或者沒有可接受的轉換)

所以我改變了操作符t o非會員:

bool operator<(const ST& lfs, const ST& rfs) 
{ 
    return lfs.sk < rfs.sk; 
} 

沒關係。所以我想知道爲什麼?

回答

4

你是缺少一個const

bool operator<(const ST &rfs) const 
{ 
    return this->sk < rfs.sk; 
} 
+0

是的,我檢查錯誤拋出的地方。'bool operator()(const _Ty&_Left,const _Ty&_Right)const'。當然,我想念常客。 – 2013-05-13 03:50:00

+0

@MIKU​​_LINK:是的,這對於能夠在const ST對象上調用操作符是必需的。 – 2013-05-13 03:59:02

+0

謝謝! @Jesse好 – 2013-05-13 04:13:55

0

我相信問題是

錯誤:二進制「<」:沒有操作員發現這需要類型的左側操作數「常量ST」(或沒有可接受的轉換)

您的成員函數bool operator<(const ST &rfs)被聲明爲非const,因此無法針對const ST調用它。

只是將其更改爲bool operator<(const ST &rfs) const,它應該工作

0

儘管有上述的答案,我建議你看看:

C++入門,第四版,第14章,第14.1

Ordinarily we define the arithmetic and relational operators as nonmember functions and we define assignment operators as members: