使用C ++样式转换将int转换为char [英] casting int to char using C++ style casting

查看:493
本文介绍了使用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, only const or volatile 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 and reinterpret_cast is needed to get the job done.

这篇关于使用C ++样式转换将int转换为char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆