C++中類的多態與虛函數的使用(三)

來源:互聯網
上載者:User

為了要解決上述不能正確分辨物件類型的問題,c++提供了一種叫做多態性

(polymorphism)
的技術來解決問題,對於常式序1,這種能夠在編譯時間就能夠確定哪個重載的成員函數被調用的情況
被稱做先
期聯編


(early binding),而在系統能夠在運行時,能夠根據其類型確定調用哪個重載的成員函數的能力
,稱為多態性

,或叫滯後聯編

(late
binding),下面我們要看的常式3,就是滯後聯編,滯後聯編正是解決多態問題的方法。

  代碼如下:

//常式3 

#include <iostream
>     
using
 namespace
 std;   
   
class
 Vehicle 

{   
public
:   
    Vehicle(float
 speed,int
 total) 
    { 

        Vehicle::speed =
 speed; 
        Vehicle::total =
 total; 
    } 
    virtual
 void
 ShowMember()//虛函數 

    { 

        cout
<<speed<<"|"<<total<<endl; 

    } 
protected
:   
    float
 speed; 
    int
 total; 

};   
class
 Car:public
 Vehicle   

{   
public
:   
    Car(int
 aird,float
 speed,int
 total):Vehicle(speed,total)   
    {   
        Car::aird =
 aird;   
    } 
    virtual
 void
 ShowMember()//虛函數,在衍生類別中,由於
繼承的關係,這裡的virtual也可以不加 

    { 
        cout
<<speed<<"|"<<total<<"|"<<aird<<endl; 

    } 
public
:   
    int
 aird; 
}; 
 
void
 test(Vehicle &temp) 

{ 
    temp.ShowMember(); 
} 
 
int
 main
()   
{   
    Vehicle a(120,4); 
    Car b(180,110,4); 

    test(a); 
    test(b); 
    cin
.get(); 

}

  多態特性的工作依賴虛函數的定義
,在需要解決多態問題的重載成員函數前,加上virtual
關
鍵字,那麼該成員函數就變成了虛函數,從上例代碼啟動並執行結果看,系統成功的分辨出了對象的真實類型,成功的調用了各自的重載成員函數。

 
 多態特性讓程式員省去了細節的考慮,提高了開發效率,使代碼大大的簡化,當然虛函數的定義也是有缺陷的,因為多態特性增加了一些資料存放區和執行指令的開
銷,所以能不用多態最好不用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.