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

查看:40
本文介绍了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 来将消息分派到子类对象,则除了析构函数之外,您可能不需要基类中的任何方法.在这种情况下,将析构函数设为 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).

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

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