简体   繁体   中英

Trouble using callback with class member function

I am having trouble compiling the following code. I am usually OK with using callback functions, but it seems that when using a member function, it has issues. Do you know what is the problem with my declaration/definition of the parameter startPlayback?

class VmapPlayer
{
        void startPlayback();
        void playAdBreak(int a, void (*callback)());
};

void VmapPlayer::playAdBreak(int a, void (*callback)())
{
    cout << a << endl;
    //callback();
}

void VmapPlayer::startPlayback()
{
    playAdBreak(5, startPlayback);     // Compile issue with "startPlayback" parameter
}

void (*callback)() declares callback as a function pointer, but startPlayback is not a free function, but a member function. This is one way to fix it:

class VmapPlayer
{
    void startPlayback();
    void playAdBreak(int a, void (VmapPlayer::*callback)());
};

void VmapPlayer::playAdBreak(int a, void (VmapPlayer::*callback)())
{
    cout << a << endl;
    (this->*callback)();
}

void VmapPlayer::startPlayback()
{
    playAdBreak(5, &VmapPlayer::startPlayback);
}

If you need more flexibility, and C++11 is available, you could use std::function<void()> to hold your callback, and fill it with a lambda expression, like [this](){ startPlayback(); } [this](){ startPlayback(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM