Mey*_*sam 14 c++ string casting explicit
为什么我需要显式转换number 0到char使用其追加到字符串之前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;
}
Run Code Online (Sandbox Code Playgroud)
更新澄清:我的目标是将一个字节(包含任何值,包括零)附加到现有的字节数组.
因为s += 0以下重载运算符+ =是不明确的
string& operator+= ( const char* s );
string& operator+= ( char c );
Run Code Online (Sandbox Code Playgroud)
0第一个函数表示一个NULL终止的字符串,第一个字符设置为NULL,而第二个函数是一个值设置为的单个字符0.
这是因为ONLY 0可以隐式转换为指针类型.没有其他整数可以隐式转换为指针类型.在您的情况下,0可以转换为const char*和char两者.转换为时const char*,它变为空指针.
因此operator+=,对于每种类型的参数都存在两个重载,因此存在关于应该进行哪种转换的含糊不清:const char*和char.
但是当你使用非零整数时,比方说65,它无法转换成const char*.因此,它可以调用的唯一函数是将char其65转换为参数的参数char.
| 归档时间: |
|
| 查看次数: |
1316 次 |
| 最近记录: |