多态的情况下释放内存:
在父类的析构函数前面加上virtual。
#include<iostream>
using namespace std;
class father
{
public:
father();
virtual ~father();//虚析构
virtual void fat();//这样才都会析构
};
void father::fat()
{
cout << "qwertuyo" << endl;
}
father::father()
{
cout << "4" << endl;
}
father::~father()
{
cout << "5" << endl;
}
class son1:public father
{
public:
son1();
~son1();
void fat();
private:
};
void son1::fat()
{
cout << "1" << endl;
}
son1::son1()
{
cout << "2" << endl;
}
son1::~son1()
{
cout << "3" << endl;
}
int main() {
father* p_fat=new son1;//匿名对象
p_fat->fat();
delete p_fat;
p_fat = NULL;
return 0;
}