C++ how to call method in derived class from base class

大城市里の小女人 提交于 2019-12-04 22:31:29

问题


What I want to do is for Execute() to run and completes it calls the Base::Done() then calls the Derived::Done(). I'm doing this because Base class Execute will do something and when its done call the Derived::Done(). I hope I'm explaining it correctly. Kind of like a listener that is called when a task completed. I'm kinda stuck on how the Base class will call the Derived class.

class Base
{
  virtual void Done(int code){};
  void Execute();
}

void Base::Execute()
{
}


class Derived : Base
{
  void Done(int code);
  void Run();
}

Derived::Done(int code)
{
}

void Derived::Run()
{
    Execute();
}

回答1:


You can use a template method:

class Base
{
 public:
  void Execute()
  {
    BaseDone(42);
    DoDone(42);
  }
 private:
  void BaseDone(int code){};
  virtual void DoDone(int) = 0;
};

class Derived : Base
{
 public:
  void Run() { Execute(); }
 private:
  void DoDone(int code) { .... }
};

Here, Base controls how its own and derived methods are used in Execute(), and the derived types only have to implement one component of that implementation via a private virtual method DoDone().




回答2:


The base class method can call the derived method quite simply:

void Base::Execute()
{
    Done(42);
}

To have the base class Done() called before the derived class, you can either call it as the first statement in the derived class method, or use the non-virtual idiom.

Here's an example of calling it at the top of the derived class method. This relies on the derived class to get it right.

void Derived::Done(int code)
{
    Base::Done(code);
}

Here's an example of using the non-virtual idiom:

class Base
{
    void Done(int code){
        // Do whatever
        DoneImpl(); // Do derived work.
    }
    virtual void DoneImpl() { };
    ...
 };

 class Derived {
     virtual void DoneImpl() { 
         // Do derived class work.
     };
     ...
 };


来源:https://stackoverflow.com/questions/17324078/c-how-to-call-method-in-derived-class-from-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!