为什么我们需要 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 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短