Why would I need to explicitly cast number 0
to char
before appending it to string using string::operator+
?
using namespace std;
int main()
{
string s = "";
s += 65; // no compile error
s += (char)0; // requires explicit cast
//s += 0; // compile error
return 0;
}
Update to clarify: My goal has been to append one byte (containing whatever value, including zero) to an existing array of bytes.
Because s += 0
is ambiguous for the following overloaded operators of +=
string& operator+= ( const char* s );
string& operator+= ( char c );
0
for the first function means a NULL terminated string with first character set to NULL, and for the second function is a single character with value set to 0
.
It is because ONLY 0
can be implicitly converted into pointer type. No other integer can implicitly be converted into pointer type. In your case, 0
can be converted into const char*
and char
both. When it is converted into const char*
, it becomes a null pointer.
So there is ambiguity as to which conversion should take place, as there are two overloads of operator+=
, for each type of arguments: const char*
and char
.
But when you use non-zero integer, say 65
, it cannot convert into const char*
. So the only function it can call is one which takes char
as argument, as 65
is converted into char
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With