使用c++风格的类型转换将int转换为char
casting int to char using C++ style casting
在传统的C语言中,你可以这样做:
int i = 48;
char c = (char)i;
//Now c holds the value of 48.
//(Of course if i > 255 then c will not hold the same value as i).
哪一个c++类型转换方法(static_cast, reinterpret_cast)适合完成这项工作?
可以隐式地在数值类型之间转换,即使这样做会失去精度:
char c = i;
但是,您可能希望启用编译器警告以避免此类潜在的有损转换。如果需要,则使用static_cast
进行转换。
其他类型转换:
-
dynamic_cast
仅适用于多态类类型的指针或引用; -
const_cast
不能改变类型,只有const
或volatile
限定符; -
reinterpret_cast
用于特殊情况,在指针或引用与完全不相关的类型之间进行转换。具体来说,它不会进行数字转换。 - c风格和函数风格的强制转换可以完成
static_cast
,const_cast
和reinterpret_cast
的任何组合。
您应该使用static_cast<char>(i)
将整型i
转换为char
。
reinterpret_cast
几乎不应该被使用,除非你想把一种类型转换成另一种根本不同的类型。
而且reinterpret_cast
是机器相关的,所以安全使用它需要完全理解类型以及编译器如何实现强制转换。
有关c++类型转换的更多信息,请参见:
- 什么时候应该使用static_cast、dynamic_cast、const_cast和reinterpret_cast ?
- http://www.cplusplus.com/doc/tutorial/typecasting/。
reinterpret_cast
不能用于此转换,代码将无法编译。根据c++ 03标准章节5.2.10-1:
Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.
此转换未在该节中列出。
long l = reinterpret_cast<long>(i)
static_cast
是这里必须使用的。
使用静态强制转换可能会导致这样的结果:
// This does not prevent a possible type overflow
const char char_max = -1;
int i = 48;
char c = (i & char_max);
要防止可能的类型溢出,可以这样做:
const char char_max = (char)(((unsigned char) char(-1)) / 2);
int i = 128;
char c = (i & char_max); // Would always result in positive signed values.
其中reinterpret_cast可能只是直接转换为char,没有任何强制转换安全性。->如果可以使用static_cast,千万不要使用reinterpret_cast。如果在类之间进行强制转换,static_cast还将确保两个类型是匹配的(对象是强制转换类型的派生)。
如果你的对象是一个多态类型,你不知道它是哪个,你应该使用dynamic_cast,它将在运行时执行类型检查,如果类型不匹配则返回nullptr。
如果你需要const_cast,你很可能做错了什么,应该考虑可能的替代方案来修复代码中const的正确性。
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 将字符串中的 int 转换为字母;
- 主.cpp:18:20:错误:从"int*"转换为"int"会失去精度 [-fa
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 如何将矢量<int>转换为字符数组?
- C++ 无法从 const int* 转换为 const_iterator
- 我不断收到错误 C2440'=':无法从"int *(__cdecl *)(int *,int *,int,int)"转换为"int *
- 如何将 int[4] 转换为 std::array<int,4>?
- 如何将data[i].int转换为vaible
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将私有矩阵形式 int 转换为双 C++
- 无法将参数 1 从 'int' 转换为 'int &'
- 将 int 转换为字符串后始终得到 0
- isspace 函数的性能警告,从 int 转换为布尔值
- 将大 int 转换为浮点数,而不舍入 c++
- 错误:无法将'uint8* {aka unsigned int*}'转换为"常量emxArray_uint8_T*"?
- 将未签名的INT转换为BCD
- 在 C++ 中将 int 转换为双精度