有没有办法强制调用父覆盖方法?

时间:2016-11-25 13:35:26

标签: c++ inheritance

基本理念看起来像

class Base
{
public:
  void some_public() {};
private:
    class CallMe
    {
        friend class Base;
    };
protected:

    virtual CallMe doSomething()
    {
        return {}
    }
};

所以私有类技巧会强制任何子类调用Base方法,如果覆盖它;

class MidChild: public Base
{
protected:
    virtual CallMe doSomething() override
    {
        //do some middle specific code

        return Base::doSomething()
    }
}

所以必须强行调用Base::doSomething()

class LastChild: public MidChild
{
protected:
    virtual CallMe doSomething() override final
    {
        //do some last child specific code
        // invoke base method because its forced to
        return Base::doSomething()
    }
}

因此我们应该调用MidChild::doSomething()而不是Base::doSomething的主要问题;因为我们也需要MidChild个动作。有没有办法强制这种调用链,即调用前一个继承级别父方法而不是基础方法?

0 个答案:

没有答案