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
- 【C/C++】C++虚析构函数的作用
- C函数指针的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 虚析构函数的作用
- 抗锯齿技术深度解析
- Q84:层级实例网格[Hierarchical Instance Grids]
- 复制虚拟机centos系统配置网卡后提示异常
- Linux下搭建nginx服务器
- SpringBoot菜鸟教程(一)
- C++ 虚析构函数的作用
- Struts2升级版本至2.5.10,高危漏洞又来了
- Android工程师进阶之路
- $.ajax()方法参数详解
- 红宝书
- Instruments 使用常见问题
- 滚动条横纵坐标位置
- iOS蓝牙编程指南 -- 核心蓝牙概述
- 序列化和反序列化