将指针'this'传递为 LPARAM
Passing 'this' pointer as LPARAM
我有如下类:
#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);
}
对第一个例子中的错误有什么解释?
您需要使用reinterpret_cast
而不是static_cast
来执行到完全不相关类型的强制转换。请参阅以下内容:何时应使用static_cast、dynamic_cast、const_cast和relpret_cast?有关不同类型的C++类型转换的更多详细信息。
static_cast
用于强制转换相关类型,如int
到float
,double
到float
,或需要太少工作的转换,如调用单参数构造函数或调用用户定义的转换函数。
LPARAM
和this
几乎不相关,所以您需要的是reinterpret_cast
:
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(GetDesktopWindow(), MyClass::proc, lparam);
如您所知,此指针是const,static_cast运算符不能丢弃const、volatile或__unaligned属性。看看MSDN上的这个链接。
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 为什么使用 "this" 指针调用派生成员函数?
- C++错误:"error: int aaa::bbb is protected within this context"
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 关于C++中具有多重继承"this"指针的说明
- 在noexcept 规范中是否允许使用"this"?
- 如何修复"error: ‘_1’ was not declared in this scope"?
- C++调用具有 *this 属性的单个帮助程序函数
- Doees the 'this' 指针参与虚函数的多态行为
- 在 c++ 中正确定义"this"关键字?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- QObject::连接无法将信号连接到*this*对象的插槽
- 析构函数中的"delete this"
- 为什么成员函数内的"this"指针为空?
- 为什么我需要在转换构造函数上引用 this->?
- "this"指针的值在对象的生存期内是否恒定?
- C++ "Invalid use of 'this' in non-member function" ,
- 将指针'this'传递为 LPARAM