非虚拟接口习惯用于两个以上的继承级别?

and*_*ykx 5 c++ inheritance class-design non-virtual-interface

非虚拟接口惯用法描述了虚拟方法是非公共自定义点的方式,公共方法是非虚拟方法,以允许基类始终控制如何调用自定义点.

这是一个优雅的习语,我喜欢使用它,但如果派生类本身就是一个基类,它是如何工作的

Dim*_*ima 5

它起作用,因为派生类可以覆盖基类的私有虚函数,即使基类函数覆盖其基类函数也是如此.

这是完全合法的:


class Parent
{
public:
  int foo() {return bar();} // the non-virtual public interface
private
  virtual int bar();
};

class Child : public Parent
{
private:
  virtual int bar();  // overrides Parent::bar()
};

class Grandchild : public Child
{
private:
  virtual int bar(); // overrides Child::bar();
};
Run Code Online (Sandbox Code Playgroud)