How do I implement a callback in C++?

前端 未结 6 2225
野性不改
野性不改 2020-12-05 19:52

I want to implement a class in c++ that has a callback.

So I think I need a method that has 2 arguments:

  • the target object. (let\'s say *myObj)
  • <
6条回答
  •  佛祖请我去吃肉
    2020-12-05 20:14

    One trick is to use interfaces instead, that way you don't need specifically to know the class in your 'MyClassWithCallback', if the object passed in implements the interface.

    e.g. (pseudo code)

    struct myinterface
    {
      void doSomething()=0;
    };
    
    class Target : public myinterface { ..implement doSomething... };
    

    and

    myinterface *targetObj; 
    void setCallback(myinterface *myObj){
        targetObj = myObj;
    };
    

    doing the callback

    targetObj->doSomething();
    

    setting it up:

    Target myTarget;
    MyClassWithCallback myCaller;
    myCaller.setCallback(myTarget);
    

提交回复
热议问题