1. 程式人生 > >c++純虛解構函式

c++純虛解構函式

純虛解構函式和虛解構函式的區別在於

純虛解構函式一般用於將類定義為抽象類,這時候有同學會問啦?抽象類不是定義一般成員方法的嗎?原因是這樣的,當我們在類裡面實在找不到可以定義為純虛擬函式的成員方法的時候,這時候可以將解構函式定義為純解構函式;

純虛構函式的實現需要注意以下幾個地方:

    通常的純虛擬函式不需要函式體,是因為我們一般不會呼叫抽象類的這個函式,只會呼叫派生類的對應函式,但是父類純虛構函式需要要函式體,因為我們知道,當子類繼承父類的時候,假如父類存在純虛擬函式,子類需要實現該函式,否則就會報錯。

    純虛解構函式也一樣,也需要實現,可是呢?能不能像通常的純虛擬函式一樣,在子類重寫即可,可是,有見過解構函式重寫的嗎,這時候的做法是給純虛解構函式指定函式體

#include<iostream>
usingnamespacestd;
classFather{
public:
virtual~Father()=0;
};
classSon:publicFather{
public:
~Son(){}
};
intmain(intargc,char*argv[])
{
cout<<"HelloWorld!"<<endl;
Father*father=newSon;
deletefather;
return0;
}

   上述程式碼報錯:     error: undefined reference to

Father::~Father()

這就是我們說到的,純虛解構函式需要指定函式體了

修改後

#include<iostream>
usingnamespacestd;
classFather{
public:
virtual~Father()=0;
};
Father::~Father()
{
cout<<"Iamfather"<<endl;
}
classSon:publicFather{
public:
~Son(){cout<<"IamSon"<<endl;}
};
intmain(intargc,char*argv[])
{
cout<<"HelloWorld!"<<endl;
Father*father=newSon;
delete
father;
return0;
}