Reputation: 93
I am trying to convert an int that represents the ASCII value of a character to a single-character string.
I tried the following, and it does not work:
string s1=(char) 97;
However, the conversion works only if I break the assignment apart like this:
string s1;
s1=(char) 97;
I am confused by this and can anyone explain the difference?
Thanks in advance!
Upvotes: 9
Views: 46191
Reputation: 15089
I tried the following, and it does not work:
string s1=(char) 97;
That's because the std::string
constructor doesn't have any overload that takes a single char
. And also, copy is elided so the constructor is called directly, operator =()
is never called (document yourself on copy elision).
the conversion works only if I break the assignment apart like this:
string s1; s1=(char) 97;
Now the copy is not elided any more, you are really calling std::string::operator =()
which does have an overload accepting a single char
.
Upvotes: 10