保证基类的也被调用。什么情况下使用比较好呢。
#include <iostream>
using namespace std;
class Base{
private:
int num1;
public:
Base():num1(10)
{
}
virtual ~Base()
{
cout<<"base"<<endl;
}
};
class Dervied:public Base{
private:
int num2;
public:
Dervied():num2(1)
{
}
~Dervied()
{
cout<<"Dervied"<<endl;
}
};
int main()
{
Base *pBase = new Dervied();
delete pBase;
}
结果会
Dervied
Base
#include<iostream>
using namespace std;
class ClxBase
{
public:
ClxBase() {};
~ClxBase() {cout<<"Do base class destruct"<<endl;};
};
class ClxDerived : public ClxBase
{
public:
ClxDerived() {};
~ClxDerived() { cout << "Do derived class destruct!" << endl; };
};
int main()
{
ClxBase *pTest = new ClxDerived;
ClxDerived derived;
delete pTest;
}
另一个例子输出的却是 :
Do base class destruct
Do derived class destruct!
Do base class destruct
说明了两个问题,只想派生类对象的基类指针需要基类声明虚系构函数才能调用派生类指针,而派生类对象却不用基类声明虚系构函数就能调用派生类指针