<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誰的對象,類析構的時候就調用誰的析構函數。運行結果如上圖所示。