β

How could it possible to assign an integer to stri

斯巴达第二季 13 阅读
c++

The snippet below could be compiled and run:

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

using namespace std;

int main(void) {
  std::map<std::string, std::string> hmap;
  hmap["a"] = "apple";
  hmap["banana"] = 1;
  for (auto item : hmap) {
    std::cout << "[" << item.first << "]" << "{" << item.second << "}\n";
  }
}

The result is:

[a]{apple}
[banana]{}

I noticed that the corresponding value of key ‘banana’ is empty. The reason is I assign an integer directly to key ‘banana’ by mistake. But how could c++ compiler allow me to do this? Why doesn’t it report a compiling error?
To reveal the truth, I write another snippet:

std::string hello;
hello = 123;

This code could also be compiled correctly!
Then I change my code to:

std::string hello = 123;

This time, the compiler complained that

map.cpp:6:23: error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]

Seems the std::string ‘s constructor and assignment operator have totally different behavier.
After checking the document, I found the reason: std::string has assignment operator for ‘char’ !( ref )

string& operator= (char c);

Thus we should be much more carefully when assign number to std::string.

c++
作者:斯巴达第二季
董昊 (Robin Dong)
原文地址:How could it possible to assign an integer to stri, 感谢原作者分享。

发表评论