<span style="font-family: Arial, Helvetica, sans-serif;">using namespace std;</span>
class C
{
public:
C()
{
cout << "construct c" << endl;
}
virtual ~C()
{
cout << "delete c" << endl;
}
virtual void showc()
{
cout << "show c" << endl;
}
};
class D : public C
{
public:
D(){
cout << "construct d" << endl;
}
~D()
{
cout << "delete d" << endl;
}
void showd()
{
cout << "show d" << endl;
}
};
int main()
{
C* c = new D;
c->showc();
delete c;
return 0;
}
注意:如果去掉基函数里面析构函数的virtual时候,那么D类析构的时候就调用不了~C()造成内存泄露。所以基函数一般都默认的加virtual,起到默认的继承作用,new谁的对象,类析构的时候就调用谁的析构函数。运行结果如上图所示。