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

Tom*_*ski 18 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;
}
Run Code Online (Sandbox Code Playgroud)

它打印'X',即ASCII为88.

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

Tar*_*ama 20

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