Sub*_*way 21 c++ int casting char
在传统的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).
Run Code Online (Sandbox Code Playgroud)
哪个c ++转换方法(static_cast,reinterpret_cast)适合完成这项工作?
Snp*_*nps 22
您应该使用static_cast<char>(i)
将整数转换i
为char
.
reinterpret_cast
应该几乎不会被使用,除非你想将一种类型转换成一种根本不同的类型.
同样reinterpret_cast
依赖于机器因此安全地使用它需要完全理解类型以及编译器如何实现强制转换.
有关C++强制转换的更多信息,请参阅:
Mik*_*our 14
你可以在数值类型之间隐式转换,即使它失去了精度:
char c = i;
Run Code Online (Sandbox Code Playgroud)
但是,您可能希望启用编译器警告以避免可能有损的转换.如果您这样做,则static_cast
用于转换.
其他演员:
dynamic_cast
仅适用于指针或对多态类类型的引用;const_cast
不能改变类型,只能改变const
或volatile
限定词;reinterpret_cast
是针对特殊情况,在指针或引用与完全不相关的类型之间进行转换.具体来说,它不会进行数字转换.static_cast
,const_cast
并且reinterpret_cast
需要完成工作. 归档时间: |
|
查看次数: |
198915 次 |
最近记录: |