如何禁止C++派生类派生自base,但允许来自另一个派生类

pac*_*rop 19 c++ inheritance

鉴于这种情况:

class GrandParent {};
class Parent : public GrandParent {};
class Child : public Parent {}; /// Ok
class Child : public GrandParent {}; /// Is it possible to force a compilation error? 
Run Code Online (Sandbox Code Playgroud)

小智 39

使GrandParent构造函数成为私有和Parent朋友.

class GrandParent
{
   friend class Parent;
   private:
   GrandParent() {}
   // ...
};
Run Code Online (Sandbox Code Playgroud)

或者,您可以GrandParents 通过使析构函数私有来权衡多态破坏:

class GrandParent
{
   friend class Parent;
   private:
   virtual ~GrandParent() {}
};

// Invalid Destruction:
GrandParent* p = new Parent;
...
delete p;
Run Code Online (Sandbox Code Playgroud)