我在访问fltk中的对象或其方法时遇到问题。 我有一个名为MyWindow的类,它是Fl_Window的子类。 所以基本上我想使用一个对象,它在main或Mywindow中声明为私有部分。我的问题是我不能这样使用它。它只允许我使用该对象,如果它被声明为全局。我可以以某种方式把它放在堆上这样:Classname * pointer = new Classname(); ?如果我可以在哪里这样做? 如果我在回调中需要该对象或其函数,回调函数将如何工作? 我应该在回调辩论中使用指针吗? 假设我想点击按钮,我需要它来对象做一些事情并改变一个值。 我知道很多问题,我真的迷路了。 有人能指出我正确的方向吗?谢谢! :)
答案 0 :(得分:0)
将数据传递到GUI的简单案例
class MyData
{
// The data model
};
class MyWindow: public FL_Window
{
MyData* m_data;
public:
void Data(MyData* data) { m_data = data; }
...
};
int main()
{
MyWindow gui;
MyData data;
// Tell the gui about the data
gui.Data(data);
...
// Setup the dialog
gui.begin();
...
gui.end();
gui.show();
return FL::run();
}
对于回调,请分两个阶段进行
class NeedingACallback
{
public:
void Setup()
{
...
FL_xxx* w = new FL_xxx(xpos, ypos, wid, hgt, name);
...
// v Pass the instance to the static
w->callback(_EventCB, this);
}
// The callback
static void _EventCB(FL_Widget* w, void* client)
{
// Convert the void* back to the instance
NeedingACallback* self = reinterpret_cast<NeedingACallback*>(client);
self->EventCB();
}
// Make life simple so you don't have to put self-> in front of
// all the instance data accessed
void EventCB()
{
// Callback for this instance of the class
}
};
编辑听起来你有多个数据实例。另一种技术是将数据作为参考。这必须在构造函数中完成。这样,m_data和main中的数据都指向相同的内存区域。
class MyWindow: public FL_Window
{
MyData& m_data;
public:
MyWindow(int wid, int hgt, MyData& data, const char* title=0)
: FL_Window(wid,hgt,title)
, m_data(data)
{
...
}
};
int main()
{
MyData data;
MyWindow gui(100, 100, data, "Call me Mr");
...
// Setup the dialog
gui.begin();
...
gui.end();
gui.show();
return FL::run();
}