为什么我们需要 C++ 中的纯虚析构函数?
在C++程序中允许纯虚析构函数没有不良影响。必须为纯虚析构函数提供函数体,因为派生类的析构函数在基类析构函数之前首先被调用,所以如果我们不提供函数体,它在对象销毁过程中将找不到任何可调用的东西,并且会发生错误.我们可以通过定义一个纯虚析构函数来轻松地创建一个抽象类。
示例代码
#include输出结果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
热门推荐
10 客户去旅游祝福语简短
11 女士祝福语幽默简短英语
12 除夕祝福语简短创意牛年
13 母亲祝福语简短微信
14 新年祝福语2026最简短
15 关于旅游的简短祝福语
16 爸妈简短婚礼祝福语大全
17 情侣520的祝福语简短
18 同学贺卡励志祝福语简短