使用C ++样式转换将int转换为char
问题描述:
在传统C语言中,您可以执行以下操作:
In traditional C you can do:
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)适合完成此工作? p>
Which of the c++ casting methods (static_cast, reinterpret_cast) is suited for getting this job done?
答
即使在数字类型失去精度的情况下,您也可以在数字类型之间进行隐式转换:
You can implicitly convert between numerical types, even when that loses precision:
char c = i;
但是,您可能希望启用编译器警告,以避免潜在的有损转换。如果这样做,则使用 static_cast
进行转换。
However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use static_cast
for the conversion.
其他类型的转换:
-
dynamic_cast
仅适用于多态类类型的指针或引用; -
const_cast
不能更改类型,只能更改const
或volatile
限定词; -
reinterpret_cast
用于特殊情况,在指针或引用与完全不相关的类型之间进行转换。具体来说,它不会进行数字转换。 - C风格和函数风格的强制转换可以执行
static_cast
,const_cast
和reinterpret_cast
才能完成工作。
-
dynamic_cast
only works for pointers or references to polymorphic class types; -
const_cast
can't change types, onlyconst
orvolatile
qualifiers; -
reinterpret_cast
is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions. - C-style and function-style casts do whatever combination of
static_cast
,const_cast
andreinterpret_cast
is needed to get the job done.