【问题标题】:Why does map<string, string> accept ints as values?为什么 map<string, string> 接受整数作为值?
【发布时间】:2015-05-29 02:18:27
【问题描述】:

我最近对此感到震惊:

#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',即 88 ASCII 码。

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

【问题讨论】:

标签: c++ dictionary


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    要完成图片,请注意:

    strings[88] = "key"; 
    

    无法编译,因为char/int 中没有 std::string 构造函数。对于charstd::string 只定义了赋值运算符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      相关资源
      最近更新 更多