如何在 C++ 中将无符号长整型 (DWORD) 重新解释为有符号长整型?

发布于 2024-11-25 00:59:35 字数 232 浏览 8 评论 0原文

我想将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

趁年轻赶紧闹 2024-12-02 00:59:35

您不需要 reinterpret_cast 将无符号类型转换为有符号类型,static_cast 即可。

You don't need reinterpret_cast to convert unsigned type into a signed one, static_cast will do.

陌路黄昏 2024-12-02 00:59:35

尝试使用 static_cast 代替。如果您尝试过度宽松的强制转换(例如当 static_cast 或 const_cast 就足够时使用reinterpret_cast),VC 会生成错误。

C++ 中有 5 种类型的强制转换,每种类型都允许您执行更多操作(授予更多权限)。最少允许的强制转换是 const 强制转换 (const_cast()),它允许您更改 const 修饰符。有静态转换 (static_cast)()),允许您执行类型安全的强制转换(例如,将基类转换为派生类)。还有动态转换 (动态_cast<衍生类型>(base_type) 允许您从一种类型转换为另一种类型,如果两者之间存在合法转换(如果没有合法转换,则返回 null最后,还有一些类型转换允许在不相关的类型之间进行转换——reinterpret_cast reinterpret_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_cast reinterpret_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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文