我有这样的课

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对象。

[UPDATE2]

将对象与全局功能链接的方法之一是通过模板对象引用。但这仅适用于全局对象:

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/

10-11 15:27