c++ - 使用 C++ 样式转换将 int 转换为 char

标签 c++ casting char int

在传统的 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 不能更改类型,只能更改 constvolatile 限定符;
  • reinterpret_cast 用于特殊情况,在指针或引用与完全不相关的类型之间进行转换。具体来说,它不会进行数字转换。
  • C-style 和 function-style casts 执行任何 static_castconst_castreinterpret_cast 的组合来完成工作。

关于c++ - 使用 C++ 样式转换将 int 转换为 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16899055/

相关文章:

c++ - 退出整个递归堆栈

c++ - 删除后立即赋值给指针

c++ - 变量损坏 C++ 字符串 Visual Studio 2005

c - 在 C 中将 int 转换为 char 时出现段错误

c - 用空格填词

c# - 如何更改大量现有代码中的命名约定?

C++ 生成警告 : dereferencing type-punned pointer will break strict-aliasing rules

kotlin - Kotlin从Any中检查了类型转换?到Map <String,Any>

C 中指向指针数组的 Char 指针

java - 将字符串转换为 unicode