将可能会被继承的父类的析构函数设置为虚函数,可以保证当我们new一个子类,然后使用基类指针指向该子类对象,释放基类指针时可以释放掉子类的空间,防止内存泄漏
class Parent
{
public:
virtual ~Parent()
{
cout
<< "delete Parent" << endl
;
}
};
class Child : public Parent
{
public:
virtual ~Child()
{
cout
<< "delete Child" << endl
;
}
};
int main(int argc
, char* argv
[])
{
Parent
* p1
= new Child();
delete p1
;
return 0;
}
输出
delete Child
delete Parent