39

在传统 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)适合完成这项工作?

4

4 回答 4

32

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

reinterpret_cast几乎不应该使用,除非您想将一种类型转换为根本不同的类型。

reinterpret_cast依赖于机器,因此安全地使用它需要完全了解类型以及编译器如何实现强制转换。

有关 C++ 强制转换的更多信息,请参见:

于 2013-06-03T14:26:31.743 回答
31

您可以在数值类型之间进行隐式转换,即使这样会丢失精度:

char c = i;

但是,您可能希望启用编译器警告以避免此类潜在的有损转换。如果你这样做,那么static_cast用于转换。

其他演员阵容:

  • dynamic_cast仅适用于多态类类型的指针或引用;
  • const_cast不能改变类型,只能改变constvolatile限定词;
  • reinterpret_cast是针对特殊情况,在指针或引用与完全不相关的类型之间进行转换。具体来说,它不会进行数字转换。
  • C 样式和函数样式转换可以执行 , 的任何组合static_castconst_cast并且reinterpret_cast是完成工作所必需的。
于 2013-06-03T14:53:31.463 回答
0

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是这里必须使用的。请参阅这个这个SO 问题。

于 2013-06-03T17:03:22.037 回答
-1

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

// 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 正确性。

于 2013-06-03T15:37:53.397 回答