It is a callback function but I can't figure out how this part works
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
is a pointer to a function returning void
and taking a Button&
parameter. It could point to something like this:
void foo(Button&){ std::cout << "Foo Button!\n"; }
This line, inside a Button
member function,
if (cb_onPress) { cb_onPress(*this); }
checks that the pointer to function is not null, and if so, calls it, passing the same instance of Button
as parameter (that is what passing *this
achieves).
Example of use:
Button b;
b.pressHandler(foo); // sets cb_onPress to point to foo
....
b.process(); // Prints "Foo Button"
although presumably the call to process happens internally, in response to an event.
if (cb_onPress) { cb_onPress(*this); }
cb_onPress
is a pointer to a function. If the pointer's a nullptr
you can't call it, so the code checks it's not beforehand.
The overall supported client usage is like this:
void myButtonEventHandler(Button& b) { ...do something when pressed... };
Button button; // make a button
button.pressHandler(myButtonEventHandler);
if (cb_onPress)
checks if cb_onPress is null pointer. In other words checks if that function was defined before. If it isn't then it calls function
cb_onPress
on that object
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.