今天试了下c++ 虚析构函数。
虚析构函数的目的是当一个基类指针指向一个派生类指针时,当delete该基类指针时,也会调用派生类的析构函数。
具体看如下代码
- #include <iostream>
- using namespace std;
- class base
- {
- public:
- base()
- {
- cout << "base: Constructor" << endl;
- };
- virtual ~base()
- {
- cout << "base: Destructor" << endl;
- };
- };
- class derived : public base
- {
- public:
- derived()
- {
- cout << "derived: Constructor" << endl;
- };
- virtual ~derived()
- {
- cout << "derived: Destructor" << endl;
- }
- };
- int main()
- {
- base *b = NULL;
- derived *p = new derived;
- b = p;
- if( b != NULL )
- {
- delete b;
- }
- return 0;
- }
函数输出:
base: Constructor
Derived: Constructor
Derived: Destructor
base: Destructor
如果base基类中的析构函数没有添加virtual关键字,函数输出如下:
base: Constructor
Derived: Constructor
base: Destructor
可以看出,当基类的析构函数添加了virtual关键字后,当其delete时,也会调用子类的析构函数。
阅读(921) | 评论(0) | 转发(0) |