我使用C++编程使用FLTK和Gui库创建了一个小游戏,我想使用倒数时钟计时器。 FLTK具有Fl::add_timeout(double t,Callback),它非常有用。问题是我想在类中使用该函数,以便在调用窗口时可以更改窗口中的任何内容。该功能必须是静态的,所以我无法访问该窗口并进行所需的更改。 Gui库仅包含对业余程序员有用的内容,因此我无法使用函数reference_to ()。有什么想法我该如何使用该功能或​​任何其他方式来实现这一目标?谢谢你的时间。我的密码:#include"GUI.h"#include<FL/Fl.h>#include"Simple_window.h"class Game : public Window { Button *b; //variables i need for the windowpublic: Game(Point xy,int w,int h, const string& name) : Window(xy,w,h,name) { b=new Button(Point(100,100),40,20,"Button"cb_button); Fl::add_timeout(1.0,TIME); } ~Game(){ delete b; } static void cb_button(Address,Address addr){ reference_to<Game>(addr).B(); } void B(){} static void TIME(void *d){ //access to the variables like this->... Fl::repeat_timeout(1.0,TIME); }};int main(){ Game win(Point(300,200),400,430,"Game"); return Fl::run();} 最佳答案 这里的要点是:您要使用函数(add_timeout)它需要c样式的回调,因此您为它提供了静态成员函数。 您不确定如何从静态方法访问实例变量。 在这里的文档http://www.fltk.org/doc-2.0/html/index.html中,您可以看到add_timeout函数将void *作为其第三个参数传递给回调函数。此处的快速解决方案是将this指针传递给add_timeout函数,然后将其转换为Game *这样访问您的成员变量:#include"GUI.h"#include<FL/Fl.h>#include"Simple_window.h"class Game : public Window{public: Game(Point xy,int w,int h, const string& name) : Window(xy,w,h,name), b(nullptr) { b = new Button(Point(100,100),40,20,"Button", cb_button); Fl::add_timeout(1.0, callback, (void*)this); } ~Game() { delete b; } static void cb_button(Address, Address addr) { reference_to<Game>(addr).B(); } void B(){} static void callback(void *d) { Game* instance = static_cast<Game*>(d); instance->b; // access variables like this-> Fl::repeat_timeout(1.0,TIME); }private: //variables you need for the window Button *b;};int main(){ Game win(Point(300,200),400,430,"Game"); return Fl::run();}关于c++ - 如何在C++和FLTK中实现倒数时钟?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32031162/
10-14 08:18