为什么我们需要 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 红包祝福语简短10字
18 周六早晨祝福语简短