How could it possible to assign an integer to string?

Robin Dong 发表于 2018年10月22日 11:12 | Hits: 1028
Tag: develope | 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:


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.

原文链接: http://donghao.org/2018/10/22/how-could-it-possible-to-assign-an-integer-to-string/

0     0