且构网

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

C++抽象类析构函数

更新时间:2022-06-09 01:44:33

在基类中只有一个纯虚析构函数很少是好的做法,但它是可能的,在某些情况下甚至是可取的.
例如,如果您依靠 RTTI 通过尝试对指向基类的指针进行 dynamic_cast 来将消息分派到子类对象,则除了析构函数之外,您可能不需要基类中的任何方法.在这种情况下,将析构函数设为 public 虚拟.

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).