C++ 虚析构函数的作用

来源:互联网 发布:美国护理学硕士知乎 编辑:程序博客网 时间:2024/06/15 07:05
一,如果析构函数不是虚的,则只将调用对应于指针类型的析构函数
#include <iostream>using namespace std;class People{public:    ~People(){        cout<<"People Object Delete."<<endl;    }};class Student : public People{    ~Student(){        cout<<"Student Object Delete."<<endl;    };};int main(){    People *p = new Student;    delete p;    return 0;}

输出结果:

People Object Delete.Process returned 0 (0x0)   execution time : 0.012 sPress any key to continue.

 

二,如果析构函数是虚的,将调用实际指向的对象的析构函数

如果指针指向的是派生类的对象,将调用派生类对象的析构函数,然后再调用基类对象的析构函数。因此,使用虚析构函数可以确保正确的析构函数调用顺序。

#include <iostream>using namespace std;class People{public:    //把基类的析构函数声明为虚的   virtual ~People(){        cout<<"People Object Delete."<<endl;    }};class Student : public People{    ~Student(){        cout<<"Student Object Delete."<<endl;    };};int main(){    People *p = new Student;    delete p;    return 0;}

输出结果:

Student Object Delete.People Object Delete.Process returned 0 (0x0)   execution time : 0.020 sPress any key to continue.

0 0
原创粉丝点击