c++ - 谁能向我解释这部分代码

标签 c++ function callback

这是一个回调函数,但我不知道这部分是如何工作的

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/

相关文章:

c++ - 使用 g++ 链接到外部库

c++ - ExpandEnvironmentStrings 不扩展我的变量

c - C 变量声明出现语法错误

python - pandas 列表操作并填充 NA

asynchronous - 如何在执行异步调用的 meteor 方法上执行回调?

C++ 转到变量

android - 使用 OpenCL 缓冲区在 OpenGL 2.0 ES 中绘制纹理

c++ - 如何将方法作为回调传递给另一个类?

函数可以定义在main()之后吗?

iphone - 如何在 iPhone 的回调中从邮件编辑器获取收件人、发件人、抄送和密件抄送字段?