您的位置:首页 > 编程语言 > C语言/C++

C++虚析构函数

2016-04-18 16:02 671 查看

如果基类中存在一个指向动态分配内存的成员变量,并且基类的析构函数中定义了释放该动态分配内存的代码,那么就应该将基类的析构函数声明为虚函数,这样可以将子类对象中的开辟的动态空间回收。

#include <iostream>
using namespace std;
//基类
class Base{
private:
int *a;
public:
Base();
virtual ~Base(){ cout<<"Base destructor"<<endl; }
};
Base::Base(){
a = new int[100];
cout<<"Base constructor"<<endl;
}
//派生类
class Derived: public Base{
private:
int *b;
public:
Derived();
~Derived( ){ cout<<"Derived destructor"<<endl; }
};
Derived::Derived(){
b = new int[100];
cout<<"Derived constructor"<<endl;
}
int main( ){
Base *p = new Derived;
delete p;
return 0;
}


运行截图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: