1. 程式人生 > >How could it possible to assign an integer to string?

How could it possible to assign an integer to string?

The snippet below could be compiled and run:

C++
1234567891011121314 #include <map>#include <string>#include <iostream>usingnamespacestd;intmain(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:

12 [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:

C++
12 std::stringhello;hello=123;

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

C++
1 std::stringhello=123;

This time, the compiler complained that

1 map.cpp:6:23:error:invalid conversion frominttoconstchar*[-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)

C++
1 string&operator=(charc);

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