2013-05-13 31 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: