如何在C++中将unsigned long(DWORD)重新解释为带符号的long?

Fel*_*bek 4 c++ reinterpret-cast unsigned-integer

我想重新解释一个unsigned long(实际上,a DWORD)作为一个signed long.我试过了:

DWORD x;
long y = reinterpret_cast<signed long>(x);
Run Code Online (Sandbox Code Playgroud)

但是,VC++ 2010 intellisense告诉我"无效的类型转换".为什么?我如何解决它?

Cat*_*lus 8

您不需要reinterpret_cast将无符号类型转换为已签名类型,static_cast也可以.

  • @ 0A0D:标准显式地命名你可以使用`reinterpret_cast`的东西,整数类型到整数类型不是该列表的一部分. (3认同)

Rei*_*man 8

尝试使用static_cast.如果您尝试过度允许的转换,VC会生成错误(例如,当static_cast或const_cast足够时使用reinterpret_cast).

C++中有5种类型的强制转换,每种类型都允许您执行更多操作(授予更多权限).最不宽容的强制转换是const casts(const_cast<int>(<const int>)),允许您更改const修饰符.有静态强制转换(static_cast<int>)(<short>)),它允许你执行类型安全的coersions(例如,铸造基础到派生).有动态强制转换(如果两者之间有合法的转换dynamic_cast<derived_type>(base_type),你可以从一种类型转换为另一种类型)如果没有转换则返回null.最后,有一些转换允许在不相关的类型之间进行转换 - reinterpret_cast 和C样式转换.reinterpret_cast<int>(<void *>)(int)<void *>

我没有很好的方法来描述这些不同类型的演员阵容,所以我将它们描述为"更宽松",因为它们中的每一个都允许你做更多.

如果您正在使用其他演员类型更适合实现目标时使用重新解释演员,VC会向您发出警告.C样式强制转换没有类似的警告以实现向后兼容性.