我在使用map类时遇到了编译器问题,并编写了以下简单程序来突出显示错误:
1 #include2 #include
我收到以下编译错误:
g ++ ./test.cc ./test.cc:在函数'int main()'中:./ test.cc:13:23:错误:'testmap.std :: map <_Key中'operator ='的模糊重载,_Tp,_Compare,_Alloc> :: operator [],std :: basic_string,std :: less>,> std :: allocator,std :: basic_string >>>((*&std :: basic_string(((const char)*)"零"),((const std :: allocator)(&std :: allocator())))))= 0'./ test.cc:13:23:注意:候选人是:在包含的文件中/usr/include/c++/4.7/string:54:0,来自./test.cc:1:/usr/include/c++/4.7/bits/basic_string.h:543:7:注意:std :: basic_string < _CharT,_ Traits,_Alloc>&std :: basic_string <_CharT,_Traits,_Alloc> :: operator =(const std :: basic_string <_CharT,_Traits,_Alloc>&)[with> _CharT = char; _Traits = std :: char_traits; _Alloc = std :: allocator; std :: basic_string <_CharT,_ Traits,_Alloc> = std :: basic_string] /usr/include/c++/4.7/bits/basic_string.h:551:7:note:std :: basic_string <_CharT,_Traits,_Alloc>& std :: basic_string <_CharT,_Traits,_Alloc> :: operator =(const _CharT*)[with _CharT = char; _Traits => std :: char_traits; _Alloc = std :: allocator; std :: basic_string <_CharT,_ Traits,_Alloc> = std :: basic_string] /usr/include/c++/4.7/bits/basic_string.h:562:7:注意:std :: basic_string <_CharT,_Traits,_Alloc>& std :: basic_string <_CharT,_Traits,_Alloc> :: operator =(_ CharT)[with _CharT = char; _Traits = std :: char_traits; _Alloc = std :: allocator; std :: basic_string <_CharT,_ Traits,_Alloc> = std :: basic_string]
我有几个问题:1.最初我认为地图"值" - 11和22正在转换为字符串.然而,在得到这个编译器错误后让我相信.以下是真正发生的事情:testmap ["one"] = 11;
如果值11,22实际上转换为字符串,那么为什么0不转换为字符串.
我正在努力理解编译器错误消息,所以我可以自己解码错误.我理解它的一部分,其中模板映射类定义被扩展,键/值是string类型.有人可以请指出错误消息中可能有助于我理解问题的部分.
任何帮助深表感谢.
艾哈迈德,谢谢你.
如果值11,22实际上转换为字符串,那么为什么0不转换为字符串.
他们不是.你的11和12分配是匹配的basic_string& operator=( CharT ch );
- 所以它将数字11和12视为字符常量 - 可能不是你想要的.假设您将它们发送到终端或打印机ala std::cout << testmap["one"];
- 11对应于"垂直标签"控制代码,可能会留下一些空白行,12对应于"换页",这可能会使打印页面的其余部分留空或清除屏幕(见http://en.wikipedia.org/wiki/ASCII).
0
在允许被隐式转换为指针的意义上是特殊的(在C++ 03 NULL
中将被定义为0
),因此转换是不明确的(即char
或const char*
?) - 参见http://en.cppreference. com/w/cpp/string/basic_string/operator%3D表示std::string operator=
s 的列表.
4.10指针转换[conv.ptr] 1空指针常量是值为零的整数文字(2.14.2)或类型为std :: nullptr_t的prvalue.空指针常量可以转换为指针类型; ...
其他整数没有这个指针转换分配 - 这就是为什么你没有得到它们的编译器错误.
你必须:
正确使用转换你的号码字符串表示,例如std::to_string()
,boost::lexical_cast
中,std::ostringstream
等,或
使用std::map<string, int>
或类似的.