1

我的班级如下:

#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);
}

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

4

3 回答 3

8

您需要使用 a reinterpret_castnot astatic_cast来强制转换为完全不相关的类型。看到这个什么时候应该使用 static_cast、dynamic_cast、const_cast 和 reinterpret_cast?有关不同类型的 C++ 强制转换的更多详细信息。

于 2012-08-27T18:06:58.477 回答
3

static_cast用于强制转换相关类型,例如intto float, and doubleto float,或需要很少努力的转换,例如调用单参数构造函数,或调用用户定义的转换函数。

LPARAM并且this几乎没有关系,所以你需要的是reinterpret_cast

LPARAM lparam =  reinterpret_cast<LPARAM>(this);
EnumChildWindows(GetDesktopWindow(), MyClass::proc, lparam);
于 2012-08-27T18:08:58.220 回答
0

如您所知, this 指针是const并且 static_cast 运算符不能丢弃constvolatile__unaligned属性。看看MSDN 上的这个链接

于 2012-08-27T18:19:52.380 回答