All these lines compile and run, with nothing printed in the output:
std::string ss{6};
ss=7;
std::cout << "ss " << ss << "\n";
I do not see any referenced constructor for std::string
that would suggest it can coerce an integer to a string, so why does the compiler not complain?
The "problem" is that a std::string
is assignable from char
and int
is implicitly convertible to char
.
Take a look at std::basic_string::operator= point (4):
basic_string& operator=( CharT ch );
EDIT
As stated in MM's comment , std::string ss{6};
calls the constructor taking initializer_list<char>
(see std::basic_string::basic_string
point (9)
)... and the problem resurfaces.
It's the
basic_string& operator=( CharT ch );
So the int
is implicitly being converted to a char
.
Try assigning the value 65
. Prints A
The line ss=7
does not call a constructor, but the assignment operator =()
.
std::string
does have an assignment operator that takes a char
, and your value 7 is converted into a char
, then the string& operator= (char c);
is called for that value. Your string will contain the ASCII BELL character.
See here for more info.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.