为什么我们需要 C++ 中的纯虚析构函数?

在 C++ 程序中允许纯虚析构函数没有不良影响。必须为纯虚析构函数提供函数体,因为派生类的析构函数在基类析构函数之前首先被调用,所以如果我们不提供函数体,它在对象销毁过程中将找不到任何可调用的东西,并且会发生错误. 我们可以通过定义一个纯虚析构函数来轻松地创建一个抽象类。

示例代码

#include <iostream>
using namespace std;

class B {
   public: virtual ~B()=0; // 纯虚析构函数
};

B::~B() {
   cout << "Pure virtual destructor is called";
}

class D : public B {
   public: ~D() {
   cout << "~Derived\n";
   }
};

int main() {
   B *b = new D();
   delete b;
   return 0;
}
输出结果
~Derived
Pure virtual destructor is called