这是一个回调函数,但我不知道这部分是如何工作的
if (cb_onPress) { cb_onPress(*this); } //fire the onPress event
class Button;
typedef void (*buttonEventHandler)(Button&);
class Button {
public:
//code
private:
//code
buttonEventHandler cb_onPress;
};
void Button::process(void)
{
//code
if (cb_onPress) { cb_onPress(*this); } //fire the onPress event
}
void Button::pressHandler(buttonEventHandler handler)
{
cb_onPress = handler;
}
最佳答案
cb_onPress
是指向返回 void
并采用 Button&
参数的函数的指针。它可能指向这样的东西:
void foo(Button&){ std::cout << "Foo Button!\n"; }
这一行,在Button
成员函数中,
if (cb_onPress) { cb_onPress(*this); }
检查指向函数的指针是否为空,如果是,则调用它,将 Button
的相同实例作为参数传递(这就是传递 *this
的目的) ).
使用示例:
Button b;
b.pressHandler(foo); // sets cb_onPress to point to foo
....
b.process(); // Prints "Foo Button"
虽然推测过程调用发生在内部,以响应 n 事件。
关于c++ - 谁能向我解释这部分代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22803973/