【问题标题】:Passing 'this' pointer as LPARAM将“this”指针作为 LPARAM 传递
【发布时间】:2012-08-27 18:03:07
【问题描述】:

我的班级如下:

#include <Windows.h>
class MyClass
{
   void A();
   static BOOL CALLBACK proc(HWND hwnd, LPARAM lParam);
};

void MyClass::A()
{
   EnumChildWindows(GetDesktopWindow(), MyClass::proc, static_cast<LPARAM>(this));
}

BOOL CALLBACK MyClass::proc(HWND hwnd, LPARAM lParam)
{
   // ...
   return TRUE;
}

当我尝试在 Visual C++ 2010 中编译它时,我收到以下编译器错误:

错误 C2440:“static_cast”:无法从“MyClass *const”转换为“LPARAM” 没有可以进行这种转换的上下文

如果我将MyClass::A的定义更改如下,那么编译成功:

void MyClass::A()
{
   EnumChildWindows(GetDesktopWindow(), MyClass::proc, (LPARAM)this);
}

第一个例子的错误解释是什么?

【问题讨论】:

    标签: c++ visual-studio-2010 winapi casting compiler-errors


    【解决方案1】:

    您需要使用reinterpret_cast 而不是static_cast 来执行转换为完全不相关的类型。有关不同类型的 C++ 强制转换的更多详细信息,请参阅此 When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

    【讨论】:

      【解决方案2】:

      static_cast 用于转换相关类型,例如intfloat,以及doublefloat,或者需要太少努力的转换,例如调用单参数构造函数,或调用用户定义的转换函数。

      LPARAMthis 几乎没有关系,所以你需要的是reinterpret_cast

      LPARAM lparam =  reinterpret_cast<LPARAM>(this);
      EnumChildWindows(GetDesktopWindow(), MyClass::proc, lparam);
      

      【讨论】:

        【解决方案3】:

        如您所知,this 指针是 const,而 static_cast 运算符不能丢弃 constvolatile__unaligned 属性。看看this link on MSDN

        【讨论】:

          猜你喜欢
          • 2023-03-30
          • 2021-10-05
          • 1970-01-01
          • 1970-01-01
          • 2016-07-20
          • 1970-01-01
          • 2012-01-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多