考虑Base类和两个Child类:

class Base
{
public:
    ~Base() = default;

    virtual void mouseCallback() = 0; // this is overriden by the Childs!

    void mouseCallback2() { std::cout << "mouseCallback2 OK" << std::endl; }//Not overriden
};

class Child1 : public Base
{
public:
    ~Child1() = default;

    void mouseCallback() override;
};

class Child2 : public Base
{
public:
    ~Child2() = default;

    void mouseCallback() override;
};

实现在哪里:
void Child1::mouseCallback()
{
    std::cout << "Child 1 OK" << std::endl;
}

void Child2::mouseCallback()
{
    std::cout << "Child 2 OK" << std::endl;
}

我有CameraVision类:
class CameraVision
{
public:
   // ...
   void init();
   static void callback(int event, int x, int y, int flags, void* userdata);
private:
   Base* mBase; // A pointer to the Base class!
}

其中包含init()方法,如下所示:
void CameraVision::init()
{
    mBase = new Child1();

    // Here I set the callback
    cv::setMouseCallback("Title", callback, &mBase);
}

这样,当鼠标发生事件时,我便拥有了这个事件,重写方法使我的应用程序崩溃。
void CameraVision::callback(int event, int x, int y, int flags, void* userdata)
{
    if (event == cv::EVENT_LBUTTONDOWN)
    {
        Base* tof = static_cast<Base*>(userdata);

        tof->mouseCallback2(); // THIS WORKS!

        // But this is what I need
        tof->mouseCallback(); // ERROR!!!!!!
    }

}

为什么我不能通过mouseCallback()的继承来使用Child1

我收到了error:
Exception thrown at 0x000000013F391938 in Demo.exe: 0xC0000005: Access violation executing location 0x000000013F391938

我期待output:
mouseCallback2 OK
Child 1 OK

最佳答案

mBase是Base *类型,那么您无需使用&,只需cv::setMouseCallback("Title", callback, mBase);
&mBase将为您提供一个指向指针的指针,因此您的static_cast不会为您提供原始的mBase指针,而是其地址。不确定第一个回调的工作方式,两者都应导致UB。

07-26 00:41