()C++基类的虚析构函数
#include<iostream>
using namespace std;
class Base
{
private:
int i;
public:
Base(){
cout << "Base count " << endl;
}
virtual ~Base(){
cout << " Base descount" << endl;
}
};
class Inherit :public Base
{
private:
int num;
public:
Inherit(){
cout << "Inherit count" << endl;
}
~Inherit(){
cout << "Inherit descout" << endl;
}
};
int main()
{
Base *p = new Inherit;
delete p;
//Base *q = new Base;
//delete q;
system("pause");
return 0;
}
当实例化继承类为基类的数据类型指针时,如果基类的析构函数不是虚函数,在delete p时,调用析构函数时,只会看指针的数据类型,而不会去看赋值的对象,这样就会造成内存泄露。因此,一般将基类中的析构函数定义为虚函数。