2015-03-25 63 views
18

我最近一直震动本:为什么map <string,string>接受int值作为值?

#include <map> 
#include <string> 
#include <iostream> 

using namespace std; 

int main() { 
    map<string, string> strings; 
    strings["key"] = 88; // surprisingly compiles 
    //map<string, string>::mapped_type s = 88; // doesn't compile as expected 

    cout << "Value under 'key': '" << strings["key"] << "'" << endl; 

    return 0; 
} 

它打印出 'X' 这是ASCII 88。

为什么字符串映射接受整数作为值?地图的文档operator[]表示它返回mapped_type&这是string&在这种情况下,它没有从int隐式转换,是吗?

+9

相关:[为什么C++允许将整数分配给字符串?](http://stackoverflow.com/q/1177704/335858)。 – dasblinkenlight 2015-03-25 12:10:02

回答

20

这是因为,正如你所说,operator[]返回std::string&,它定义了operator= (char c)。您的注释示例不会调用赋值运算符,它是copy-initialization,它将尝试调用该类的显式构造函数,其中在std::string中没有适用的构造函数。

3

要完成图片,请注意:

strings[88] = "key"; 

不能编译,因为从char/int没有std::string构造。对于charstd::string只定义了赋值运算符。

相关问题