且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++抽象类析构函数

更新时间:2022-11-09 22:46:16

在基类中仅具有纯虚拟析构函数很少是一种好习惯,但是

例如,如果您依靠RTTI通过在指向基类的指针上尝试dynamic_cast来将消息调度到子类对象,则可能不需要基类中的方法(析构函数除外)。在这种情况下,请将析构函数设为公共虚拟。

Having only a pure virtual destructor in the base class is rarely a good practice, but it is possible and, in certain cases, even desirable.
For instance, if you rely on RTTI to dispatch messages to a subclass object by attempting a dynamic_cast on the pointer to the base class, you may need no methods in the base class except the destructor. In this case, make the destructor public virtual.

由于除析构函数外没有其他虚拟方法,因此必须使其纯净,以防止创建基类的对象。

在这里,至关重要的是向该析构函数提供空的主体(即使它是 = 0!)

Since you have no other virtual methods except the destructor, you have to make it pure in order to prevent the creation of the objects of the base class.
Here, it is crucial to provide the empty body to that destructor (even though it is "=0"!)

struct AbstractBase {
     virtual ~AbstractBase() = 0;
}

AbstractBase::~AbstractBase() {
}

具有主体可以创建子类对象(前提是子类定义了析构函数且未将其设置为纯析构函数。)

Having the body allows the creation of subclass objects (provided that the subclass defines the destructor and does not set it as pure).