How could it possible to assign an integer to string?
阿新 • • 發佈:2018-12-23
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 |
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:
12 | std::stringhello;hello=123; |
This code could also be compiled correctly!
Then I change my code to:
1 | std::stringhello=123; |
This time, the compiler complained that
1 | map.cpp:6:23:error:invalid conversion from‘int’to‘constchar*’[-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)
1 | string&operator=(charc); |
Thus we should be much more carefully when assign number to std::string.