为什么map<string,string>接受整数作为值?

Why does map<string, string> accept ints as values?

本文关键字:string 整数 gt map lt 为什么      更新时间:2023-10-16

我最近被这个震惊了:

#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。

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

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

要完成图片,请注意:

strings[88] = "key"; 

不编译,因为没有来自 char/intstd::string构造函数。对于charstd::string只定义赋值运算符。