[英]Can anyone explain me this part of the code
这是一个回调函数,但我不知道这部分是如何工作的
如果(cb_onPress){cb_onPress(* this); } //触发onPress事件
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"
尽管大概是对事件的响应,但流程调用在内部发生。
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
在那个物体上
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.