c++中虚析构函数
2024-10-19 00:30:56
当指向基类的指针指向新建立的派生类对象而且基类和派生类都调用new向堆申请空间时,必须将基类的析构函数声明为虚函数,从而派生类的析构函数也为虚函数,这样才能在程序结束时自动调用它,从而将派生类对象申请的空间归还给堆。
附上一段代码诠释上述概念:
#include <iostream>
#include <string>
using namespace std;
class base{
char *p;
public:
base(int sz,char *bptr){
p=new char[sz];
strcpy(p,bptr);
cout<<"constructor base"<<endl;
}
virtual ~base(){
delete []p;
cout<<"destructor base\n";
}
};
class derive:public base{
char *pp;
public:
derive(int sz1,int sz2,char *bp,char *dptr):base(sz1,bp){
pp=new char[sz2];
strcpy(pp,dptr);
cout<<"destructor derive\n";
}
~derive(){
delete []pp;
cout<<"destructor derive\n";
}
};
int main(){
base *px=new derive(,,"base","derive");
delete px;
return ;
}
运行结果:
如果不使用虚构函数,派生类动态申请的内存空间不能正常地退还给堆,程序的运行结果为:
#include <iostream>
#include <string>
using namespace std;
class base{
char *p;
public:
base(int sz,char *bptr){
p=new char[sz];
strcpy(p,bptr);
cout<<"constructor base"<<endl;
}
~base(){
delete []p;
cout<<"destructor base\n";
}
};
class derive:public base{
char *pp;
public:
derive(int sz1,int sz2,char *bp,char *dptr):base(sz1,bp){
pp=new char[sz2];
strcpy(pp,dptr);
cout<<"destructor derive\n";
}
~derive(){
delete []pp;
cout<<"destructor derive\n";
}
};
int main(){
base *px=new derive(,,"base","derive");
delete px;
return ;
}
特殊地,抽象类中的纯析构函数必须定义为:
virtual ~shape()=0
{} //大话号{}不能省略
最新文章
- ubuntu14.04上Virtualbox安装win7(使用Ghost镜像安装,启用USB设备支持,设置共享目录)
- jQuery源码分析系列:Callback深入
- 【CentOS】ifconfig命令 :command not found &; yum命令 :cannot find a valid baserl for repo: base/7/x86_64
- VC++ CStatic控件背景透明且改变其文本时,文字重叠解决方法
- 【Swift学习】Swift编程之旅---属性(十四)
- [转]easyui 全部图标
- CentOS GO 语言环境的搭建
- Larave 多图片上传
- 201521123121 《Java程序设计》第14周学习总结
- python基础(数组)
- hightcharts 如何修改legend图例的样式
- Python 入门基础11 --函数基础4 迭代器、生成器、枚举类型
- 如何在Centos7上安装和使用ZFS
- PHPExcel exception: “Could not close zip file … ”报错
- 44-python-三维画图
- Python通用网络爬虫脚本
- 51nod1821 最优集合 贪心
- C3P0数据库连接池的java实现
- vue 同页面不同参数
- spring aop切面编程实现操作日志步骤
热门文章
- 无线网卡连接网络后共享给本地有线网卡使用(Win10)
- Visual Studio2013 配置opencv3.3.0 x64系统
- Json 简记
- web版ssh的使用
- Codeforces Round #546 (Div. 2) E 推公式 + 线段树
- lambda 匿名函数
- 执行PowerShell脚本的时候出现";在此系 统上禁止运行脚本";错误
- 第一个SpringBoot应用
- Spring boot 使用 configuration 获取的属性为 null
- vue-cli3 DllPlugin 提取公用库