当指向基类的指针指向新建立的派生类对象而且基类和派生类都调用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(5,7,"base","derive"); delete px; return 0; }
运行结果:
如果不使用虚构函数,派生类动态申请的内存空间不能正常地退还给堆,程序的运行结果为:
#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(5,7,"base","derive"); delete px; return 0; }
特殊地,抽象类中的纯析构函数必须定义为:
virtual ~shape()=0
{} //大话号{}不能省略
时间: 2024-10-30 16:24:05