在C++中,如何确定类是否是继承链中的最后一个类/子类?即在基类的另一端

Mik*_*son 3 c++ inheritance children class

我在简单地写这个问题时遇到了问题,但基本上在类中有一个函数可能是继承链中的最后一个类,或者它可能不是.在此函数内部,如果类级函数是继承链中的最后一个函数,则将调用第二个函数.显示我正在谈论的内容比解释它要容易得多,所以:

让我们说我有Z级.

Z派生自Y,它源自X,源自W.

所有类都有一个名为Execute()的虚函数.

Z.Execute()要求完成Y.Execute(),这需要完成X.Execute(),这需要完成W.Execute().

因此,Z的Execute()函数如下所示:

void Z::Execute(void)
{
   Y::Execute();

   // do Z's stuff!
   return;
}
Run Code Online (Sandbox Code Playgroud)

同样,Y的Execute()函数如下所示:

void Y::Execute(void)
{
   X::Execute();

   // do Y's stuff!
   return;
}
Run Code Online (Sandbox Code Playgroud)

等等继承链.

但Y,X和W都不是抽象的,因此每个都可以实例化,并且可能是也可能不是继承链中的最后一个类.

这是我需要知道的.最后一个Execute()需要调用DoThisAtEndOfExecute().需要在类的内部调用DoThisAtEndOfExecute(),即.它不会公开.

因此它不能在X的Execute()中,因为如果类是Y,它将被调用得太早.它不能在Y的Execute()中,因为该类可能是Z.它不能在Z的Execute()中,因为如果该类是Y,X或W,则该函数永远不会被调用.

那么有没有办法让一个类判断它是否已被继承FROM?基本上,相当于:

if (!IAmTheParentOfSomething)
   DoThisAtEndOfExecute();
Run Code Online (Sandbox Code Playgroud)

这是怎么做到的?我承认,对于包含要执行的类的函数,更简单的方法是:

X.Execute();
X.DoThisAtEndOfExecute();
Run Code Online (Sandbox Code Playgroud)

但这不是这个代码的一个选项.

Sev*_*yev 7

如果将Execute拆分为非虚拟部件和虚拟部件,我认为可以实现您想要的功能.前者将运行后者,然后调用DoThisAtEndOfExecute.像这样:

class X
{
public:
    void Execute()
    {
        ExecuteImpl(); //That one's virtual, the derived classes override it
        DoThisAtEndOfExecute();
    }

protected:
    virtual void ExecuteImpl()
    {
        //Whatever was in the legacy Execute
    }
}
Run Code Online (Sandbox Code Playgroud)

Y和Z覆盖ExecuteImpl()并调用基数.这样,DoThisAtEndOfExecute()在ExecuteImpl()的大多数派生版本完成之后运行,而不知道实际的类.

  • AKA"模板方法". (2认同)