在传统的 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
进行转换。
其他 Actor :
dynamic_cast
仅适用于多态类类型的指针或引用;const_cast
不能更改类型,只能更改const
或volatile
限定符;reinterpret_cast
用于特殊情况,在指针或引用与完全不相关的类型之间进行转换。具体来说,它不会进行数字转换。- C-style 和 function-style casts 执行任何
static_cast
、const_cast
和reinterpret_cast
的组合来完成工作。
关于c++ - 使用 C++ 样式转换将 int 转换为 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16899055/