【发布时间】:2015-07-13 21:32:22
【问题描述】:
我正在尝试制作一个类似按钮的对象 (Smart_Button),其中包含自己的回调函数。该对象是由 My_Window 构造函数创建的,但是当我点击 gui 按钮时它的内存地址与 My_Window 构造函数内部的地址不同。我想启用一些需要 Smart_Buttons 彼此具有指针的附加功能,但我不能,因为地址发生了变化。
奇怪的是,如果我在 My_window 中定义回调函数(就像我为 site_parent_cb 所做的那样),我会得到我期望的行为。当前程序的输出是:
site_parent_cb in constructor: 0xbfc20c6c
site_local_cb in constructor: 0xbfc20c48
(when I hit the "parent" button)
this: 0xbfc20c6c
(when I hit the "local" button)
this: 0xbfc20b90
我的代码如下。另外,我的 include 是从 Struoustrups 的 Programming Principles and Practice Using C++ Book 中调用文件。这些文件是一些 FLTK 功能的包装器,可在此处获得:http://www.stroustrup.com/Programming/PPP2code/
任何理解行为的帮助将不胜感激。我的主要问题是这是否来自我自己的代码我不理解,或者它是否是简化 FLTK 包装器的特性。
#include "GUI.h"
namespace Graph_lib {
struct Smart_Button : Button {
Smart_Button(Point tl, int w, int h, Callback cb);
Smart_Button(Point tl, int w, int h);
void print_address();
private:
static void cb_pressed(void*, void*);
};
Smart_Button::Smart_Button(Point tl, int w, int h, Callback cb)
:Button(tl, w, h, "parent", cb)
{
}
Smart_Button::Smart_Button(Point tl, int w, int h)
:Button(tl, w, h, "local", cb_pressed)
{
}
void Smart_Button::cb_pressed (void*, void* pw){static_cast<Smart_Button*>(pw)->print_address();}
void Smart_Button::print_address(){
cout << "this: " << this << endl;
}
struct My_Window : Window {
My_Window();
Smart_Button site_local_cb;
Smart_Button site_parent_cb;
private:
static void cb_pressed(void*, void*);
};
My_Window::My_Window()
:Window(Point(100,100),200,200,"Some App"),
site_parent_cb(Point( 50, 50), 40, 40, cb_pressed),
site_local_cb(Point(100, 50), 40, 40)
{
cout << "site_parent_cb in constructor: " << &site_parent_cb << endl;
cout << "site_local_cb in constructor: " << &site_local_cb << endl;
attach(site_parent_cb);
attach(site_local_cb);
}
void My_Window::cb_pressed (void*, void* pw){static_cast<My_Window>(pw)->site_parent_cb.print_address();}
};
int main(int argc, char **argv) {
using namespace Graph_lib;
My_Window game;
return gui_main();
}
【问题讨论】:
标签: c++ pointers static callback fltk