如何实现虚函数回调?
我正在使用 wxWigets,但我想这个问题更多的是如何实现虚函数回调。这是我的代码的(非常)简化版本:
// MyGUI.h
Class MyGUI : public wxFrame {
...
protected:
virtual void onFeedButton_cb( wxCommandEvent& event ) { event.Skip(); }
...
}
// Animal.h
Class Animal {
public:
void Feed();
}
一个简单的问题:如何实现 onFeedButton_cb 回调,以便它可以访问 Animal 的 Feed() 函数?即在运行时回调必须能够访问 Animal 的实例。
I am using wxWigets, but I suppose this question is more of how to implement callbacks that are virtual functions. This is a (very) simplified version of my code:
// MyGUI.h
Class MyGUI : public wxFrame {
...
protected:
virtual void onFeedButton_cb( wxCommandEvent& event ) { event.Skip(); }
...
}
// Animal.h
Class Animal {
public:
void Feed();
}
A trivial question: How do I implement the onFeedButton_cb callback so that it can access Animal's Feed() function?? i.e. during run time the callback must have access to an instance of Animal.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
定义一个为您调用该虚拟函数的非虚拟函数,并将该非虚拟函数附加到回调中。
请注意,这种转换正是
std::mem_fun
在 STL 函子的幕后所做的事情,尽管它依赖于编译时而不是运行时多态性。Define a non-virtual function that calls the virtual function for you, and attach the non-virtual function to the callback.
Note that this kind of conversion is exactly what
std::mem_fun
does under the covers for STL functors, though it relies on compile time rather than runtime polymorphism.鉴于您评论中的解释,似乎您需要:
使
MyGUI.h
中的代码了解Animal
为指向唯一
Animal
实例的指针定义也许类似this:
另请参阅 Singleton 模式。
Given the explanations in your comments, it seems you need to:
make the code in
MyGUI.h
aware ofAnimal
define a global storage for a pointer to the only
Animal
instancePerhaps something like this:
See also the Singleton pattern.
对我有用的是:
What worked for me was this: