【发布时间】:2014-03-06 06:33:18
【问题描述】:
目前我正在学习 Win32 和 C++,并完成了我的第一个应用程序。现在我想将代码从功能样式转换为 OOP。这是我的代码的缩短版本:
#include <Windows.h>
class BaseWindow {
public:
BaseWindow ();
virtual LRESULT CALLBACK WndProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) abstract;
bool Register ();
};
BaseWindow::BaseWindow () {}
bool BaseWindow::Register () {
WNDCLASSEXW wnd = {0};
wnd.lpfnWndProc = &BaseWindow::WndProc; // Error | How to point to the derived class's WndProc
// Some other properties
return RegisterClassExW(&wnd) != NULL;
}
class MainWindow : BaseWindow {
using BaseWindow::Register;
public:
MainWindow();
bool Register ();
LRESULT CALLBACK WndProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
};
MainWindow::MainWindow () : BaseWindow () {}
LRESULT CALLBACK MainWindow::WndProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
// Handling messages
}
如何将派生类的WndProc绑定到BaseWindow::Register中父类的wnd.lpfnWndProc?
【问题讨论】:
-
有问题吗?并且您注册的
WndProc需要是static或与班级友好的独立外部函数。您不能将简单的成员函数用作注册的 wndproc 回调。 -
谢谢。我不知道。有没有办法将
lpfnWndProc绑定到类的成员? -
有,但不一定是微不足道的(至少对初学者来说不是)。一种方法can be seen here。通常,它涉及提供您的对象指针作为 windows api
CreateWindow创建参数的一部分,然后将该指针存储在窗口实例的窗口额外字节中以供将来在调度消息时使用。阅读该链接。它不是(恕我直言)理想,但它是一种方式。
标签: c++ winapi pointers derived-class base-class