这是一个回调函数,但我无法弄清楚这部分是如何工作的
if (cb_onPress) { cb_onPress(*this); } 触发新闻事件
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); }
检查指向函数的指针是否不为 null,如果是,则调用它,将相同的 Button
实例作为参数传递(这就是传递 *this
实现的目标)。
使用示例:
Button b;
b.pressHandler(foo); // sets cb_onPress to point to foo
....
b.process(); // Prints "Foo Button"
尽管大概对进程的调用发生在内部,以响应 n 事件。
if (cb_onPress) { cb_onPress(*this); }
cb_onPress
是指向函数的指针。 如果指针是nullptr
则无法调用它,因此代码不会事先检查它。
支持的总体客户端使用情况如下所示:
void myButtonEventHandler(Button& b) { ...do something when pressed... };
Button button; // make a button
button.pressHandler(myButtonEventHandler);
如果 (cb_onPress)
检查cb_onPress是否为空指针。换句话说,检查该函数之前是否定义过。如果不是,则调用函数
cb_onPress
在该对象上