原文地址:http://blog.csdn.net/zhangjunbob/article/details/52915841
正在做一个鼠标绘图程序,在一个class中需要调用鼠标响应函数setMouseCallback,
由于setMouseCallback中的mousecallback不支持调用non-static function,遇到了很多问题,现总结解决方法。
myclass.h中
class MyClass
{
private:
void on_Mouse(int events, int x, int y);
static void onMouse(int events, int x, int y, int, void* userdata);
}
myclass.cpp中
void MyClass::onMouse(int events, int x, int y, int, void* userdata)
{
// Check for null pointer in userdata and handle the error
MyClass* temp = reinterpret_cast<MyClass*>(userdata);
temp->on_Mouse(events, x, y);
}
void MyClass::on_Mouse(int events, int x, int y)
{
switch (events)
{
case CV_EVENT_LBUTTONDOWN:
//your code here
break;
case CV_EVENT_MOUSEMOVE:
//your code here
break;
case CV_EVENT_LBUTTONUP:
//your code here
break;
}
}
在cpp函数中调用setMouseCallback时采用:
void MyClass::Initial()
{
//......
setMouseCallback(windowname, MyClass::onMouse, this);
}
setMouseCallback中的this很重要,不然MyClass* temp不能得到当前的MyClass实例。