虛函數是指一個類中你希望重載的成員函數,當你用一個基類指標或引用指向一個繼承類對象的時候,你調用一個虛函數,實際調用的是繼承類的版本。(引用)一旦類的一個函式宣告為虛函數,那麼衍生類別的對應函數也成為虛函數。
下面通過程式解釋虛函數:
#include<iostream><br />using namespace std;</p><p>class Parent<br />{<br />public:<br /> char data[20];<br /> void Function1();<br /> virtual void Function2(); // 這裡聲明Function2是虛函數<br />};</p><p>void Parent::Function1()<br />{<br /> cout<<"This is parent,function1"<<endl;<br />}</p><p>void Parent::Function2()<br />{<br /> cout<<"This is parent,function2"<<endl;<br />}</p><p>class Child:public Parent<br />{<br /> void Function1();<br /> void Function2();<br />};</p><p>void Child::Function1()<br />{<br /> cout<<"This is child,function1"<<endl;<br />}</p><p>void Child::Function2()<br />{<br /> cout<<"This is child,function2"<<endl;<br />}</p><p>int main(void)<br />{<br /> //這裡只是為了說明虛函數,所以類的定義等指標應用很不合規範<br /> Parent parent;<br /> Child child;<br /> Parent *p; // 定義一個基類指標<br /> char ch;<br /> cin>>ch;<br /> if(ch=='a') // 如果輸入一個小寫字母c<br /> p=&child; // 指向繼承類對象<br /> else<br /> p=&parent; // 否則指向基類對象<br /> p->Function1(); // 這裡在編譯時間會直接給出Parent::Function1()的入口地址。<br /> p->Function2(); // 注意這裡,執行的是哪一個Function2<br /> return 0;<br />}</p><p>/*<br />a<br />This is parent,function1<br />This is child,function2</p><p>b<br />This is parent,function1<br />This is parent,function2<br />*/
輸入一個小寫字母a,得到下面的結果:
This is parent,function1
This is child,function2
因為我們是用一個Parent類的指標調用函數Fuction1(),雖然實際上這個指標指向的是Child類的對象,但編譯器無法知道這一事實(直到啟動並執行時候,程式才可以根據使用者的輸入判斷出指標指向的對象),它只能按照調用Parent類的函數來理解並編譯,所以我們看到了第一行的結果。
第二行的結果我們注意到,Function2()函數在基類中被virtual關鍵字修飾,也就是說,它是一個虛函數。虛函數最關鍵的特點是“動態聯編”,它可以在運行時判斷指標指向的對象,並自動調用相應的函數。如果我們在運行上面的程式時任意輸入一個非c的字元,結果如下:
This is parent,function1
This is parent,function2
請注意看第二行,它的結果出現了變化。程式中僅僅調用了一個Function2()函數,卻可以根據使用者的輸入自動決定到底調用基類中的Function2還是繼承類中的Function2,這就是虛函數的作用。我們知道,在MFC中,很多類都是需要你繼承的,它們的成員函數很多都要重載,比如編寫MFC應用程式最常用的CView::OnDraw(CDC*)函數,就必須重載使用。把它定義為虛函數(實際上,在MFC中OnDraw不僅是虛函數,還是純虛函數),可以保證時刻調用的是使用者自己編寫的OnDraw。虛函數的重要用途在這裡可見一斑。