2013-12-24 23 views
4

我使用的地图类,当运行到编译器的问题,并写了下面的简单程序以突出错误:STL地图<字符串,字符串>,0值赋给一个关键原因编译错误

1 #include <string> 
    2 #include <map> 
    3 
    4 using namespace std; 
    5 
    6 int main() 
    7 { 
    8  map<string, string> testmap; 
    9 
10 
11  testmap["one"] = 11; 
12  testmap["two"] = 22; 
13  testmap["zero"] = 0; 
14  // testmap["zero"] = 10; 
15 
16  return 0; 
17 } 

我得到以下编译错误:

g++ ./test.cc ./test.cc: In function 'int main()': ./test.cc:13:23: error: ambiguous overload for 'operator=' in 'testmap.std::map<_Key, _Tp, _Compare, _Alloc>::operator[], std::basic_string, std::less >, >std::allocator, std::basic_string > > >((* & std::basic_string(((const char*)"zero"), ((const std::allocator)(& std::allocator()))))) = 0' ./test.cc:13:23: note: candidates are: In file included from /usr/include/c++/4.7/string:54:0, from ./test.cc:1: /usr/include/c++/4.7/bits/basic_string.h:543:7: note: 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: note: 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;

  1. 如果值11,22实际上转换为字符串,那么为什么0不转换为字符串。

  2. 我在努力理解编译器错误信息,所以我可以自己解码错误。我理解它的一些部分,其中模板映射类定义通过key/value为string类型进行扩展。有人可以请我指出可能帮助我理解问题的错误消息部分。

任何帮助,非常感谢。

谢谢, 艾哈迈德。

+5

您可以将一个字符分配给一个字符串,并且可以分配一个指针。两者都符合资格。 – chris

回答

13

If the values 11, 22 is in fact converted to string, then why is 0 not converted to a string.

他们不是。你的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),并且由于该原因转换是不明确(即charconst char*?) - 请参阅http://en.cppreference.com/w/cpp/string/basic_string/operator%3D以获取std::string operator=的列表。

4.10 Pointer conversions [conv.ptr] 1 A null pointer constant is an integer literal (2.14.2) with value zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; ...

其他整数没有这个指针转换分配 - 这就是为什么你没有得到它们的编译器错误。

必须之一:

  • 正确转换您的号码字符串表示,例如使用std::to_string(),boost::lexical_caststd::ostringstream等。或
  • 使用std::map<string, int>或类似的代替。
相关问题