用来做基类的类的析构函数一般都是虚函数。原因是因为用一个基类的指针删除一个派生类的对象时,派生类的析构函数会被调用。
#include <conio.h>
#include <iostream.h>
#include <string>
using namespace std;
class base
{
public:
base(){}
~base(){cout<<"base 的析构函数"<<endl;}
virtual void dosomething(){cout<<"base 的dosomething 函数"<<endl;}
};
class derived : public base
{
~derived(){cout<<"derived 的析构函数 "<<endl;}
void dosomething (){cout<<"derived 的dosomething 函数"<<endl;}
};
int main()
{
base * temp = new derived;
temp->dosomething();
delete temp;
getch();
return 0;
}