如何在 C++ 中将无符号长整型 (DWORD) 重新解释为有符号长整型?
我想将 unsigned long
(实际上是 DWORD
)重新解释为 signed long
。我尝试过:
DWORD x;
long y = reinterpret_cast<signed long>(x);
但是,VC++2010智能感知告诉我“无效的类型转换”。为什么?我该如何修复它?
I want to reinterpret an unsigned long
(actually, a DWORD
) as a signed long
. I tried:
DWORD x;
long y = reinterpret_cast<signed long>(x);
However, VC++2010 intellisense tells me "Invalid type conversion". Why? How do I fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要
reinterpret_cast
将无符号类型转换为有符号类型,static_cast
即可。You don't need
reinterpret_cast
to convert unsigned type into a signed one,static_cast
will do.尝试使用 static_cast 代替。如果您尝试过度宽松的强制转换(例如当 static_cast 或 const_cast 就足够时使用reinterpret_cast),VC 会生成错误。
C++ 中有 5 种类型的强制转换,每种类型都允许您执行更多操作(授予更多权限)。最少允许的强制转换是 const 强制转换 (
const_cast()
),它允许您更改 const 修饰符。有静态转换 (static_cast)()
),允许您执行类型安全的强制转换(例如,将基类转换为派生类)。还有动态转换 (动态_cast<衍生类型>(base_type)
允许您从一种类型转换为另一种类型,如果两者之间存在合法转换(如果没有合法转换,则返回 null最后,还有一些类型转换允许在不相关的类型之间进行转换——reinterpret_castreinterpret_cast()
和 C 风格类型转换(int)操作
我没有一个好的方法来描述这些不同类型的强制转换,因此我将它们描述为“更宽松”,因为它们中的每一个都允许您执行更多
。当其他强制转换类型之一更适合实现您的目标时,重新解释强制转换。 C 样式强制转换没有类似的向后兼容性警告。
try static_cast instead. VC generates an error if you try an excessively permissive cast (like using reinterpret_cast when static_cast or const_cast will suffice).
There are 5 types of casts in C++, each of which allows you to do more (grants more permissions). The least permissive casts are const casts (
const_cast<int>(<const int>)
) which allow you to change the const modifier. There are static casts (static_cast<int>)(<short>)
) which allow you to perform type safe coersions (cast base to derived, for example).There are dynamic casts (dynamic_cast<derived_type>(base_type)
that allow you to cast from one type to another if there is a legal conversion between the two (and that return null if there is no conversion). Finally, there are casts that allow conversion between unrelated types - reinterpret_castreinterpret_cast<int>(<void *>)
and C style cast(int)<void *>
.I don't have a good way of describing these different types of casts, so I describe them as "more permissive" because each of them allows you to do more.
VC warns you if you are using a reinterpret cast when one of the other cast types would be more appropriate to achieve your goal. C style casts don't have a similar warning for backwards compatibility.