在没有显式调用的情况下强制在父方法之前执行父方法 [英] Force execution of parent's method before child's method without explicit call

查看:70
本文介绍了在没有显式调用的情况下强制在父方法之前执行父方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C ++应用程序,但遇到了一个问题: 我有一个派生自抽象类A的类B,该类具有一些事件处理方法.第三类C派生自B,并且必须重新实现某些B方法.有没有一种方法可以在调用C的方法之前隐式调用B的方法?

I'm working on a c++ app and I'm facing a problem: I have a class B derived from the abstract class A that has some event handling methods. A third class C is derived from B and must reimplement some of B methods. Is there a way to implicitly call B's method before calling C's one?

类图:

class A
{
    virtual void OnKeyPress(event e)=0;
};
class B : public A
{
    virtual void OnKeyPress(event e)
    {
    print("Keypressed: "+e)
    };
};
class C : public B
{
    void OnKeyPress(event e)
    {
    //DoSomething
    }
}

我想出的解决方法之一是使用C :: foo()中的B :: foo()从C调用父方法.这种方法有效,但是要由开发人员记住将调用添加到方法的主体中.

One of the workaround I figured out is to call the parent's method from C using, say, B::foo() inside C::foo(). This works but it is up to the developer to remember to add the call in the method's body.

另一种方法是定义一个新的虚拟方法,该子方法将覆盖子方法,而父方法将在其"OnKeyPress"方法中调用.

The other is to define a new virtual method that the child will override and that the parent will call inside its "OnKeyPress" method.

谢谢你, 3mpty.

Thank you, 3mpty.

推荐答案

您必须显式调用基类方法.

You have to explicitly call the base class method.

class C : public B
{
    virtual void OnKeyPress(event e)
    {
        B::OnKeyPress(e);
        // Do stuff
    }
};

只需重新阅读您的问题.....

Just re-read your question.....

最好的办法是在B中实现方法,该方法最后调用要由C实现的另一个受保护的虚拟方法.

Best thing to do is to implement method in B that lastly calls an additional protected virtual method to be implemented by C.

class B : public A
{
  protected:
       virtual void AdditionalKeyStuff(event e) { }

  public:

    virtual void OnKeyPress(event e)
    {
        // Do B Stuff

        // Finally give decendants a go.
        AdditionalKeyStuff(e)
    }
};


class C : public B
{
  protected:

    virtual void AdditionalKeyStuff(event e)
    {
        // Do only C stuff
    }
};

如果您想强制任何后代将其覆盖,则可以将B中的AdditionalKeyStuff(...)设为纯虚拟.

And you could make the AdditionalKeyStuff(...) in B pure virtual if you want to force any decendants to override it.

这篇关于在没有显式调用的情况下强制在父方法之前执行父方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆