【发布时间】:2011-07-15 15:22:07
【问题描述】:
我想将unsigned long(实际上是DWORD)重新解释为signed long。我试过了:
DWORD x;
long y = reinterpret_cast<signed long>(x);
但是,VC++2010 intellisense 告诉我“类型转换无效”。为什么?我该如何解决?
【问题讨论】:
标签: c++ reinterpret-cast unsigned-integer
我想将unsigned long(实际上是DWORD)重新解释为signed long。我试过了:
DWORD x;
long y = reinterpret_cast<signed long>(x);
但是,VC++2010 intellisense 告诉我“类型转换无效”。为什么?我该如何解决?
【问题讨论】:
标签: c++ reinterpret-cast unsigned-integer
您不需要reinterpret_cast 将无符号类型转换为有符号类型,static_cast 即可。
【讨论】:
reinterpret_cast on,整数类型到整数类型不是该列表的一部分。
尝试使用 static_cast。如果您尝试过度宽松的强制转换(例如在 static_cast 或 const_cast 就足够时使用 reinterpret_cast),VC 会生成错误。
C++ 中有 5 种类型的强制转换,每一种都允许您做更多事情(授予更多权限)。最不容许的转换是 const 转换 (const_cast<int>(<const int>)),它允许您更改 const 修饰符。有静态转换 (static_cast<int>)(<short>)) 允许您执行类型安全强制转换(例如,将基转换为派生)。还有动态转换(dynamic_cast<derived_type>(base_type) 允许您从一种类型转换为另一种类型 if 两者之间存在合法转换(如果没有转换,则返回 null)。最后,还有允许在不相关类型之间进行转换的转换 - reinterpret_cast reinterpret_cast<int>(<void *>) 和 C 风格转换 (int)<void *>。
我没有很好的方式来描述这些不同类型的演员表,所以我将它们描述为“更宽松”,因为它们中的每一个都可以让你做更多的事情。
VC 会在您使用重新解释转换时发出警告,而此时其他转换类型中的一种更适合实现您的目标。 C 样式转换没有类似的向后兼容性警告。
【讨论】: