如何在C++和FLTK中实现倒计时时钟?

How to implement a countdown clock in C++ and FLTK?

我使用 C++ 编程中的 FLTK 和 Gui 库创建了一个小游戏,我想使用倒计时时钟计时器。 FLTK 有非常有用的 Fl::add_timeout(double t,Callback)。问题是我想在我的 class 中使用该函数,因此我可以在 window 调用时更改任何内容。该函数必须是静态的,所以我无法访问 window 并进行我想要的更改。 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 window
public:
   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();
}

这里的要点是:

  1. 您想使用函数(add_timeout)

  2. 它需要一个 c 风格的回调,所以你给它一个静态成员函数。

  3. 您不确定如何从静态方法访问实例变量。

从此处的文档:http://www.fltk.org/doc-2.0/html/index.html,您可以看到 add_timeout 函数将 void* 作为其第三个参数传递给您的 callback.The 此处的快速修复是将 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();
}