C++ 虚析构函数的作用

一,如果析构函数不是虚的,则只将调用对应于指针类型的析构函数
#include 

using namespace std;

class People{
public:
    ~People(){
        cout<<"People Object Delete."<

输出结果:

People Object Delete.

Process returned 0 (0x0)   execution time : 0.012 s
Press any key to continue.

 

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

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

#include 

using namespace std;

class People{
public:
    //把基类的析构函数声明为虚的
   virtual ~People(){
        cout<<"People Object Delete."<

输出结果:

Student Object Delete.
People Object Delete.

Process returned 0 (0x0)   execution time : 0.020 s
Press any key to continue.

你可能感兴趣的:(C++)