使用c++风格的类型转换将int转换为char

casting int to char using C++ style casting

本文关键字:int 转换 char 类型转换 c++ 风格 使用      更新时间:2023-10-16

在传统的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不能改变类型,只有constvolatile限定符;
  • reinterpret_cast用于特殊情况,在指针或引用与完全不相关的类型之间进行转换。具体来说,它不会进行数字转换。
  • c风格和函数风格的强制转换可以完成static_cast, const_castreinterpret_cast的任何组合。

您应该使用static_cast<char>(i)将整型i转换为char

reinterpret_cast几乎不应该被使用,除非你想把一种类型转换成另一种根本不同的类型。

而且reinterpret_cast是机器相关的,所以安全使用它需要完全理解类型以及编译器如何实现强制转换。

有关c++类型转换的更多信息,请参见:

    什么时候应该使用static_cast、dynamic_cast、const_cast和reinterpret_cast ?
  • http://www.cplusplus.com/doc/tutorial/typecasting/。

reinterpret_cast不能用于此转换,代码将无法编译。根据c++ 03标准章节5.2.10-1:

Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.

此转换未在该节中列出。

long l = reinterpret_cast<long>(i)

static_cast是这里必须使用的。

使用静态强制转换可能会导致这样的结果:

// This does not prevent a possible type overflow
const char char_max = -1;
int i = 48;
char c = (i & char_max);

要防止可能的类型溢出,可以这样做:

const char char_max = (char)(((unsigned char) char(-1)) / 2);
int i = 128;
char c = (i & char_max); // Would always result in positive signed values.

其中reinterpret_cast可能只是直接转换为char,没有任何强制转换安全性。->如果可以使用static_cast,千万不要使用reinterpret_cast。如果在类之间进行强制转换,static_cast还将确保两个类型是匹配的(对象是强制转换类型的派生)。

如果你的对象是一个多态类型,你不知道它是哪个,你应该使用dynamic_cast,它将在运行时执行类型检查,如果类型不匹配则返回nullptr。

如果你需要const_cast,你很可能做错了什么,应该考虑可能的替代方案来修复代码中const的正确性。