添加纯虚析构函数定义的目的是什么?

发布于 2024-10-21 18:02:06 字数 294 浏览 5 评论 0原文

灵感来源:C++——为什么我们应该在类定义之外定义纯虚析构函数?

下面的代码实际上做了什么?

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

Object::~Object() { /*...*/ }

我认为纯虚函数的目的是强制子类实现该特定函数。如果是这样的话,那为什么还要在虚拟基类中实现相同的功能呢?

Inspired by: C++ -- why should we define the pure virtual destructor outside the class definition?

What does the following code actually do?

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

Object::~Object() { /*...*/ }

I thought that the point of a pure virtual function was to force subclasses to implement that particular function. If that is the case, then why bother implementing the same function in the virtual base class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北城挽邺 2024-10-28 18:02:06

此代码阻止您创建 Object 实例,同时允许您创建子类。

销毁对象时,会调用父类的析构函数,因此它必须存在。无论析构函数是否是纯虚拟的,这都适用。仅当显式调用纯虚拟成员函数时,才需要定义它,Foo:theFunc()

This code prevents you from creating an instance of Object, while at the same time allowing you to create subclasses.

When destroying an object, the destructor of the parent class will be called, so it must exist. This applies whether the destructor is pure virtual or not. A pure virtual member function only needs to be defined if you explicitly call it, Foo:theFunc().

不必你懂 2024-10-28 18:02:06

对于纯虚拟析构函数,没有办法“强迫”任何人在派生类中实现它。编译器会为你写一个。此外,编译器编写的析构函数(在派生类中)将调用父析构函数 - 因此您最好为父代编写一个实现。

因此,总结一下:

  1. 不是析构函数的纯虚函数不需要实现,因为您不会期望程序员调用它。
  2. 纯虚拟析构函数必须有一个实现,因为编译器必然会从子类中的析构函数(程序员和编译器编写的)调用它。

In the case of a pure virtual destructor, there is no way of 'forcing' anyone to implement it in derived classes. The compiler will write one for you. In addition, the compiler written destructor (in a derived class) will call the parent destructor - so you had better have written an implementation for the parent.

So, to summarise:

  1. A pure virtual function that is not a destructor need not have an implementation as you would not expect a programmer to call it.
  2. A pure virtual destructor must have an implementation since the compiler is bound to call it from destructors (both programmer and compiler written) in child classes.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文