如何禁止派生类从基C++派生,但允许从另一个派生类派生
How to forbid C++ derived class to derive from base, but allow from another derived class
给定以下场景:
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");
如果您尝试将父类更改为祖父类,编译器会给您错误
相关文章:
- 检查一个类型是否直接派生自"enable if"上下文中的另一个类型(是其子类型)
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 两个抽象类,派生自同一个基类.如何访问从一个抽象类到另一个抽象类的指针
- C++多态性:如何测试一个类是否派生自另一个基类
- 派生类不能用另一个基类的成员重载基类中的私有成员
- 通过 c++ 中的 udp 套接字将派生类对象从一个进程发送到另一个进程
- 是否可以在引用另一个派生类的派生类中声明复制构造函数?
- 无法从派生类型的作用域访问另一个实例的受保护成员
- 如何在另一个类的向量中调用派生类的析构函数
- 从具有相同基数的另一个派生类调用派生类的非 const 方法
- 从另一个类模板类型推导派生的类模板
- 如何从另一个类的基类访问派生类中的受保护成员
- 从基类(车辆)继承方法,从派生类(汽车)继承值,以使用 C++ 在另一个派生类(车道)中实现
- 用于确定一个类是否派生自另一个类的代码说明
- 如何使用派生类中的虚拟函数,该函数在另一个具有基类参数的类中声明
- 如何禁止派生类从基C++派生,但允许从另一个派生类派生
- 一个可以将参数化的类作为参数传递给另一个将由另一个派生的类吗
- 如何创建从另一个派生的两个ATL接口
- 如何正确删除从另一个DLL接收的派生对象
- 是否可以使用相同的基类从另一个派生对象访问派生对象