类方法的回调(C ++) [英] Callbacks from a class method (C++)

查看:133
本文介绍了类方法的回调(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Button类。
当我点击这个按钮,它的selected()方法被调用。

I have a Button class. When I click this button, it's selected() method is called.

//Button.cpp
void Button::selected(){
//Do Something
}

//Player.cpp
void Player::Jump(){
//Jump!
}

我也有一个Player类。
我想要这样,当我点击按钮,播放器方法的Jump()
被调用。我想我可以只链接Player类与按钮。
但是我意识到按钮类将有很多其他用途,而不是
只是让我的玩家跳。 (即:一个菜单选择器?让玩家移动?等等)

I also have a Player class. I wanted to make it so that when I click the button, the player method's Jump() is called. I suppose I could just link the Player class with the button. But then I realized that the button class is going to have many other uses, and not just letting my player jump. (ie: a menu selector? make the player move? etc.)

所以我想包括一些回调,但我不太熟悉

So I was thinking of including some kind of a callback, but I'm not too familiar with them and I'm having trouble understanding some tutorials I've read.

有人可能告诉我如何使用selected()方法来接受任何函数/方法作为参数并在方法体中执行?

Could someone show me how I would use the selected() method to take in any function/method as a parameter and execute it in the method body?

推荐答案

这里是一个函数方法, / p>

Here's a functor approach where you pass a function as an argument:

template <typename functor_t>
void Button::selected(functor_t func){
  // ...
  func();
  // ...
}

参数可以是函数指针,或一个函数对象:

The argument can be a function pointer, or a function object:

 struct functor {
   void operator()() {
     // stuff
   }
 };

 void function() {
   // stuff
 }


$ b b

使用指向成员的指针调用 void method()

struct foo {
  void bar() {
    std::cout << "hello";
  }
};

template <typename class_t>
void function(class_t& c, void (class_t::* mp)()) {
  (c.*mp)();
}

foo x;
function(x, &foo::bar);

这篇关于类方法的回调(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆