基本理念看起来像
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
个动作。有没有办法强制这种调用链,即调用前一个继承级别父方法而不是基础方法?