C ++如何在基类中调用派生类中的方法

C ++如何在基类中调用派生类中的方法

问题描述:

我想要做的是 Execute()运行并完成它调用 Base :: Done()然后调用 Derived :: Done()。我这样做是因为 Base class 执行会做一些事情,当它完成调用 Derived :: Done()。我希望我正确地解释它。种类似于一个任务完成时调用的侦听器。我很想知道 Base 类如何调用 Derived 类。

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();
}


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) { .... }
};

这里, Base 派生类型在 Execute()中使用,派生类型只需通过私有虚方法实现该实现的一个组件 DoDone()

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().