How can I pass a class member function as a callback?

前端 未结 12 2030
忘掉有多难
忘掉有多难 2020-11-22 04:58

I\'m using an API that requires me to pass a function pointer as a callback. I\'m trying to use this API from my class but I\'m getting compilation errors.

Here is

12条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 05:49

    A simple solution "workaround" still is to create a class of virtual functions "interface" and inherit it in the caller class. Then pass it as a parameter "could be in the constructor" of the other class that you want to call your caller class back.

    DEFINE Interface:

    class CallBack 
    {
       virtual callMeBack () {};
    };
    

    This is the class that you want to call you back:

    class AnotherClass ()
    {
         public void RegisterMe(CallBack *callback)
         {
             m_callback = callback;
         }
    
         public void DoSomething ()
         {
            // DO STUFF
            // .....
            // then call
            if (m_callback) m_callback->callMeBack();
         }
         private CallBack *m_callback = NULL;
    };
    

    And this is the class that will be called back.

    class Caller : public CallBack
    {
        void DoSomthing ()
        {
        }
    
        void callMeBack()
        {
           std::cout << "I got your message" << std::endl;
        }
    };
    

提交回复
热议问题