当指向基类的指针指向新建立的派生类对象而且基类和派生类都调用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

{}                          //大话号{}不能省略

最新文章

  1. ubuntu14.04上Virtualbox安装win7(使用Ghost镜像安装,启用USB设备支持,设置共享目录)
  2. jQuery源码分析系列:Callback深入
  3. 【CentOS】ifconfig命令 :command not found &amp; yum命令 :cannot find a valid baserl for repo: base/7/x86_64
  4. VC++ CStatic控件背景透明且改变其文本时,文字重叠解决方法
  5. 【Swift学习】Swift编程之旅---属性(十四)
  6. [转]easyui 全部图标
  7. CentOS GO 语言环境的搭建
  8. Larave 多图片上传
  9. 201521123121 《Java程序设计》第14周学习总结
  10. python基础(数组)
  11. hightcharts 如何修改legend图例的样式
  12. Python 入门基础11 --函数基础4 迭代器、生成器、枚举类型
  13. 如何在Centos7上安装和使用ZFS
  14. PHPExcel exception: “Could not close zip file … ”报错
  15. 44-python-三维画图
  16. Python通用网络爬虫脚本
  17. 51nod1821 最优集合 贪心
  18. C3P0数据库连接池的java实现
  19. vue 同页面不同参数
  20. spring aop切面编程实现操作日志步骤

热门文章

  1. 无线网卡连接网络后共享给本地有线网卡使用(Win10)
  2. Visual Studio2013 配置opencv3.3.0 x64系统
  3. Json 简记
  4. web版ssh的使用
  5. Codeforces Round #546 (Div. 2) E 推公式 + 线段树
  6. lambda 匿名函数
  7. 执行PowerShell脚本的时候出现&quot;在此系 统上禁止运行脚本&quot;错误
  8. 第一个SpringBoot应用
  9. Spring boot 使用 configuration 获取的属性为 null
  10. vue-cli3 DllPlugin 提取公用库