如何使用回调使工作变得简单按钮类?
How to make work simple button class with callback?
如何使简单的按钮类在按下时调用自定义函数。一些代码示例:
class Button
{
public:
Button();
Draw();
Press();
SetCallback(void(*cback)());
priate:
void (*callback)();
}
void Button::SetCallback(void(*cback)())
{
callback = cback;
}
class GameState
{
...
}
class MenuState : public GameState
{
Button *btn;
}
class Game
{
...
}
bool Game::Init()
{
std::unique_ptr<GameState> menu = std::unique_ptr<MenuState>(new MenuState);
}
void Game::PopState(){
states.pop_back();
}
如何在此示例中将按钮中的回调设置为游戏::P opState(( 函数。我需要然后我按下按钮,它调用游戏::P opState 函数。
您正在寻找的是有关函数指针的教程,可以在此处找到。
如果需要传递参数,则按钮函数指针应具有指向 Game 对象的指针或引用,因为成员函数需要引用(哪个对象拥有函数调用(。如果游戏类中的 popstate 函数是私有的,则可能需要将其设为公共函数或好友函数。
您应该能够通过将字符串引用替换为对 Game 对象的引用来修改以下示例。如果您需要更通用的回调,请查看模板(更好但有点复杂(或类型双关语(通常被认为是不好的做法(
#include <iostream>
#include <string>
class Button
{
public:
void SetCallback(void(*cback)(std::string&));
void Press(std::string str){
//Make sure some sort of check is done in order to prevent undefined behavior from a call
if(callback != nullptr)
callback(str);
}
Button(){
callback = nullptr;
}
private:
void (*callback)(std::string&);
};
void Button::SetCallback(void(*cback)(std::string&))
{
callback = cback;
}
//Method 2 for calling function
void DoStuff(std::string& str){
std::cout << str;
}
int main(void){
Button btn;
//Method 1 for calling function, replace body with Game.PopStates();
auto foo = [](std::string& str){ std::cout<<str.size();};
btn.SetCallback(foo);
btn.Press("A");
//Method 2 for calling function
btn.SetCallback(&DoStuff);
btn.Press("nPressed Button");
return 0;
}
游戏的函数指针应该是这样的:
void SetCallback(void(*cback)(Game&));
你可以这样称呼它:
auto foo = [](Game& g){ g.DoStuffInClass(); };
btn.SetCallback(foo);
btn.Press(game);
上面的示例工作正常,通常就是您需要做的,但本文将更深入地介绍成员函数指针。本文的主要内容是 typedef 是编写成员函数指针的另一种方法,如下所示:
typedef int (Fred::*FredMemFn((char x, float y(; 请这样做!
但是,上述所有操作(当使用 PopStates 实现时(都是将按钮回调锁定为使用 Game 对象调用的 void 函数,这限制了您使用按钮的能力。如果要允许在没有 Game 对象的情况下执行操作的特殊情况,则可以使用指针而不是引用,但无论哪种方式,Game 对象都必须找到某种方式放入回调中。
相关文章:
- 在c++中用vector填充一个简单的动态数组
- (C++)分析树以计算返回错误值的简单算术表达式
- 问:如何使用C++中的按钮从窗口打开窗口
- 我的简单if-else语句是如何无法访问的代码
- 使用简单类型列表实现的指数编译时间.为什么
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何在BST的这个简单递归实现中消除警告
- QML按钮点击功能执行顺序
- 当用户超过按钮点击限制时报告
- 一种在C++中读取TXT配置文件的简单方法
- 关于简单C++函数(is_palindrome)的逻辑的问题
- 函数计算用户按下按钮的频率
- 热键/按钮,根据需要进行编译,但不运行(在F5和Ctrl+Shift+B之间)
- 显示错误输出的简单数组排序程序
- FLTK:按下哪个按钮 - 将数字传递给按钮的回调 (lambda)
- 如何使用回调使工作变得简单按钮类?
- 尝试将简单按钮绑定到SFGUI中的OnClick功能
- C++中按钮的简单信号
- 用Arduino编程一个简单的按钮LED电路
- Qt -使用按钮控制线程的简单示例