gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:50:05 25 4
gpt4 key购买 nike

我使用 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 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* 作为其传递给回调的第三个参数。此处的快速修复是将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com