不要被這個(gè)名字嚇住涝焙,其實(shí)他就是普通的析構(gòu)函數(shù)變“虛”了,也就是增加了多態(tài)性码耐。它的主要功能就是確保繼承體系中的對(duì)象正確釋放巍举。例子:
class Base
{
public:
virtual ~Base(){}
};
class Derived :public Base
{
public:
Derived()
{
pointer = new int[10];
}
~Derived()
{
delete []pointer;
}
int *pointer;
};
void main()
{
Derived *d = new Derived();
Base *b = d;
delete b;//此處如果沒有虛析構(gòu)函數(shù)畴嘶,則只會(huì)調(diào)用基類的析構(gòu)函數(shù)蛋逾,那么派生類中分配的內(nèi)存就沒辦法釋放,造成泄露窗悯。所以区匣,如果發(fā)生繼承,一定要把基類析構(gòu)函數(shù)定義為虛函數(shù)蒋院。
}