gpt4 book ai didi

c++ - 将类中的方法作为参数传递

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:53:58 26 4
gpt4 key购买 nike

我有这样一个类

class Keyboard
{
public:
Keyboard(void);
~Keyboard(void);
void SetHook(HINSTANCE hInstance);
LRESULT CALLBACK keyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam);
};


LRESULT CALLBACK Keyboard::keyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
bool bControlKeyDown=0;
bool caps = GetKeyState(VK_CAPITAL) < 0;

...

void Keyboard::SetHook(HINSTANCE hInstance)
{
KeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, Keyboard::keyboardHookProc, hInstance, NULL);
}

但是声明

KeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, Keyboard::keyboardHookProc, hInstance, NULL);

导致编译错误

Error   7   error C3867: 'Keyboard::keyboardHookProc': function call missing argument list; use '&Keyboard::keyboardHookProc' to create a pointer to member

如果我更改为 '&Keyboard::keyboardHookProc' 也会出错,当我转换为 '(HOOKPROC) &Keyboard::keyboardHookProc' 时也会出错

请大家帮忙

最佳答案

这是 C 回调的常见错误。

Keyboard::keyboardHookProc必须是静态的。

[更新]

你必须找到其他方法来获得 Keyboard如果您想对 Keyboard 进行操作,请反对此静态方法static Keyboard::keyboardHookProc 中的对象.如果你有一个Keyboard你可以使用 singleton模式,如果不是那么每个静态方法都必须有自己的 Keyboard目的。

[更新2]

将对象与全局函数联系起来的方法之一是通过模板对象引用。但这仅适用于全局对象:

class Keyboard
{
public:
Keyboard();
~Keyboard(void);
LRESULT keyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam);
};

LRESULT Keyboard::keyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
}
// global function interface
template <Keyboard& k>
LRESULT CALLBACK keyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
return k.keyboardHookProc(nCode, wParam, lParam);
}


Keyboard k; // global keyboard

int main()
{
// this works
SetWindowsHookEx(0, keyboardHookProc<k>, NULL, NULL);
}

关于c++ - 将类中的方法作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12652493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com