如何禁止派生类从基C++派生,但允许从另一个派生类派生

How to forbid C++ derived class to derive from base, but allow from another derived class

本文关键字:派生 另一个 C++ 禁止 何禁止      更新时间:2023-10-16

给定以下场景:

class GrandParent {};
class Parent : public GrandParent {};
class Child : public Parent {}; /// Ok
class Child : public GrandParent {}; /// Is it possible to force a compilation error? 

GrandParent构造函数设为私有,Parent为好友。

class GrandParent
{
   friend class Parent;
   private:
   GrandParent() {}
   // ...
};

或者,您可以通过将析构函数设为私有来权衡GrandParents的多态销毁:

class GrandParent
{
   friend class Parent;
   private:
   virtual ~GrandParent() {}
};
// Invalid Destruction:
GrandParent* p = new Parent;
...
delete p;

解决此问题的另一种方法是使用"模板魔术"。您应该在子类声明之后添加此代码:

 #include <type_traits>
 class Child : public Parent
 {
 };
 static_assert(std::is_base_of<Parent, Child>::value, "Child must derive Parent");

如果您尝试将父类更改为祖父类,编译器会给您错误

相关文章: