加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用C风格的铸造转换int到char

发布时间:2020-12-16 03:16:35 所属栏目:百科 来源:网络整理
导读:这个问题在这里已经有一个答案: Regular cast vs. static_cast vs. dynamic_cast 8 Why use static_castint(x) instead of (int)x?9个 在传统的C你可以做: int i = 48;char c = (char)i;//Now c holds the value of 48. //(Of course if i 255 then c will
这个问题在这里已经有一个答案:> Regular cast vs. static_cast vs. dynamic_cast 8
> Why use static_cast<int>(x) instead of (int)x?9个
在传统的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风格和函数风格的casts做任何组合的static_cast,const_cast和reinterpret_cast需要完成工作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读