谁能解释我这部分代码
Can anyone explain me this part of the code
这是一个回调函数,但我无法弄清楚这部分是如何工作的
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
在该对象上
相关文章:
- 在java中解决这段代码时面临循环中的问题
- 这行代码在C++类中意味着什么
- 我是如何在这段代码中出现分段错误的
- 如何优化这部分代码:
- 一个简单的 win32 多线程代码.这能行吗?
- 我在具有递归函数的这部分代码中收到此错误
- 我很难为 if/else 语句编写此赋值的代码.这是第一堂编程课
- 如何确保这部分代码仅由一个线程运行(在 openmp 中)
- C++代码:这里面出了什么问题
- C++构造函数代码..这叫什么
- 不完全理解这部分代码
- 为什么这部分代码仍在执行
- 这部分 C++ 代码有什么问题
- 在一个独立的C++程序中编译用C++编写的Festival代码的部分
- 如何使clang格式跳过c++代码的部分
- 是否有更简单的方法来编写这部分代码
- 编译器是否优化了这部分代码(const getter)
- 如何加速这段c++代码(特别是阶乘和幂部分)
- 有没有办法在C++中以编程方式执行 adb 命令?这C++部分代码是使用 android Studio 中的 ndk b
- 谁能解释我这部分代码