为什么map <string,string =“”>将int作为值接受?</string,>

时间:2015-03-25 12:05:52

标签: c++ dictionary

我最近对此感到震惊:

#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;
}

它打印&#39; X&#39;这是ASCII中的88。

为什么字符串映射会将int作为值接受?地图operator[]的文档说它会返回mapped_type&,在这种情况下string&并且它没有int的隐式转换,它?

2 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:3)

要完成图片,请注意:

strings[88] = "key"; 
由于std::string / char没有int构造函数,

无法编译。对于charstd::string仅定义赋值运算符。