【发布时间】:2011-04-23 03:45:26
【问题描述】:
我无法编译一些东西。我不明白抛出的错误 由编译器。下面是一些说明问题的代码。
#include <map>
using namespace std;
class Thing
{
public:
Thing(int n):val(n) {}
bool operator < (const Thing& rhs) const
{
return val < rhs.val;
}
int getVal() { return val; }
private:
int val;
};
int main(int argc, char* argv[])
{
std::map<Thing, int> mymap;
Thing t1(1);
Thing t2(10);
Thing t3(5);
mymap[t1] = 1; // OK
mymap.insert(t1); // Compile error
}
现在编译器错误信息:
test.cpp: 在函数'int main(int, char**)’: test.cpp:34: 错误: 否 调用的匹配函数 'std::map, std::allocator > >::insert(Thing&)’ /usr/include/c++/4.4/bits/stl_map.h:499: 注:候选人是: 标准::对, std::_Select1st >, _Compare, typename _Alloc::rebind >::other>::iterator, bool> std::map<_key _tp _compare _alloc>::insert(const std::pair&) [with _Key = Thing, _Tp = int, _Compare = std::less, _Alloc = std::allocator >] /usr/include/c++/4.4/bits/stl_map.h:539: 注意:类型名称 std::_Rb_tree<_key std::pair std::_select1st>, _Compare, typename _Alloc::rebind >::other>::iterator std::map<_key _tp _compare _alloc>::insert(typename std::_Rb_tree<_key std::pair std::_select1st>, _Compare, typename _Alloc::rebind >::other>::iterator, const std::pair&) [with _Key = 事物,_Tp = int,_Compare = std::less,_Alloc = std::allocator >]
这是什么意思?我需要在 Thing 中定义其他方法或运算符以使其编译吗?
【问题讨论】:
-
getVal()方法也可能是const-qualified。 -
@ArunSaha - 谢谢,这只是一个例子。