C++ 虚析构函数的作用

一,如果析构函数不是虚的,则只将调用对应于指针类型的析构函数
#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 s
Press 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 s
Press any key to continue.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值