C ++抽象类析构函数 [英] C++ abstract class destructor

查看:122
本文介绍了C ++抽象类析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在父类中仅使用纯虚拟析构函数来创建抽象类是否是一种好习惯(并且可能)吗?

Is it good practice (and is it possible) to create an abstract class using only a pure virtual destructor in the parent class?

这里是一个示例

class AbstractBase {
public:
    AbstractBase () {}
    virtual ~AbstractBase () = 0;
};

class Derived : public AbstractBase {
public:
    Derived() {}
    virtual ~Derived() {}
};

否则,如果派生类的属性和构造函数都相同,如何创建抽象类

Otherwise how can I create an abstract class if the attributes and constructors of the derivatives class are all the same while the other method are totally different?

推荐答案

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

例如,如果您依靠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).

这篇关于C ++抽象类析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆