基类:
class A
{
public:
A() : i(new int(10))
{
cout << "A构造" << endl;
}
virtual ~A()
{
cout << "A释放" << endl;
delete i;
}
private:
int *i;
};
派生类:
class B : public A
{
public:
B() : j(new int(10))
{
cout << "B构造" << endl;
}
~B()
{
cout << "B释放" << endl;
delete j;
}
private:
int *j;
};
主函数:
int main(int argc, const char *argv[])
{
A *b = new B;//基类指针b指向派生类对象B
delete b;//手动释放b中内存
return 0;
}
如果基类中析构函数不加virtual,那么派生类中的析构函数将不会调用,产生内存泄漏,结果:
加上virtual后