我有简单的UI类,我需要将UI元素实例发送到每个元素的回调,所以我可以(很像在javascript中)操纵调用回调的元素。
这需要将this
的实例发送到注册为回调的函数。我该怎么做?
现状:
class Opencv_Button {
private:
bool (*callback)(void*); //Callback WITHOUT the current button isntance
//bool(*callback)(Opencv_Button, void*); //this is CALLBACK I WANT instead
void* callback_param; //parameter set by user
bool state;
bool mouse(int, int, int);
public:
Opencv_Button(int, int, int, int);
void setCallback(bool(*)(void*), void*);
//void setCallback(bool(*)(Opencv_Button, void*), void*); //This is what I WANT TO USE
void draw(Mat*, bool);
void val(const char*);
char value[30];
};
现在,有一个调用回调的函数:
bool Opencv_Button::mouse(int mx, int my, int button)
{
if(/*click conditions satisfied*/)
{
/*CLICK!!!*/
if(callback!=0)
callback(callback_param);
/*Instead I WANT:*/
//callback(*this/*some THIS instance*/, callback_param);
return true;
}
return false;
}
所以,我可以在回调中做这样的事情:
bool buttonCallback(Opencv_Button*but, void*param) {
but->val("I was clicked!!!");
}
答案 0 :(得分:1)
你非常接近。快速解决方法是确保您的回调采用指针并传递this
:
bool (*callback)(Opencv_Button*, void*);
void setCallback(bool(*)(Opencv_Button*, void*), void*);
并致电:
callback(this, callback_param);
但是,使用引用可能会更好。您可以让您的函数引用Opencv_Button
:
bool (*callback)(Opencv_Button&, void*);
void setCallback(bool(*)(Opencv_Button&, void*), void*);
然后用:
调用它callback(*this, callback_param);
您的buttonCallback
将如下所示:
bool buttonCallback(Opencv_Button& but, void* param) {
but.val("I was clicked!!!");
}
答案 1 :(得分:0)
将回调定义为
bool (*callback)(Opencv_Button*, void*);
一切都很顺利。