【问题标题】:Why does reinterpret_cast<int>(lParam); generate C2440 error?为什么 reinterpret_cast<int>(lParam);生成 C2440 错误?
【发布时间】:2020-06-21 11:40:21
【问题描述】:

我有一个典型的带有签名的 C++/MFC/32 位 Windows 消息处理程序 LRESULT CMyFrame::OnMyMessage(WPARAM wParam, LPARAM lParam)

我已经写了这两行,更喜欢第一行而不是第二行:

int iError = reinterpret_cast<int>(lParam);
int iWorks = (int)lParam;

我第一次收到 C2440 错误: 错误 C2440:“reinterpret_cast”:无法从“LPARAM”转换为“int”

但是第二个编译得很好

这是 C++,而不是 C,因此我更喜欢第一个而不是第二个。我做错了什么?

【问题讨论】:

  • static_cast 不起作用吗?

标签: c++ visual-studio visual-studio-2008 mfc reinterpret-cast


【解决方案1】:

reinterpret_cast 验证它可以在编译时重新解释底层位结构,并且它发现您正在尝试将 LPARAM 更改为 int 并且不喜欢它。

改用static_cast

更多信息:LPARAMdefined as LONG_PTR,它本身就是:

#if defined(_WIN64)
 typedef __int64 LONG_PTR; 
#else
 typedef long LONG_PTR;
#endif

【讨论】:

  • 由于这是为 32 位编译的,LONG 应该毫无问题地转换为 int,所以 reinterpret_cast 应该可以工作吗?
  • @franji1 不,long 的大小不需要与int 相同,它本身就是一个单独的类型。因此,reinterpret_cast 不允许这样做,即使尺寸与您的平台/构建相匹配(如前所述,static_cast 就是为此目的而制作的)。
  • @franji1 没有。 reinterpret_cast 不能用于从一种整数类型到另一种整数类型的转换,而是使用static_cast 代替。始终先尝试static_cast,然后仅在需要时尝试reinterpret_castC-style castreinterpret_cast 之前尝试 static_cast
  • 我讨厌 C++ 中的 c 风格强制转换。 static_cast 是!
  • 请注意,static_cast 仍然很危险,即使编译为 32 位也是如此。 LPARAM 毕竟可以存储一个指针(这就是它最初的用途)。将其转换为 signed int 随后会引入非常微妙的错误,具体取决于对结果执行的操作。
猜你喜欢
  • 1970-01-01
  • 2012-11-20
  • 2013-09-22
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多