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

來源:互聯網
上載者:User

但是在實際工作中,很可能會碰到對象所屬類不清的情況,下面我們來看一下衍生類別成員作為函數參數傳遞的例子,代碼如下:

//常式2 

#include <iostream
>     
using
 namespace
 std;   
   
class
 Vehicle 

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

        Vehicle::speed=speed; 
        Vehicle::total=total; 
    } 

    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;   

    } 
    void
 ShowMember() 
    { 

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

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


    temp.ShowMember(); 

 
void
 main
()   

    Vehicle a(120,4); 
    Car b(180,110,4); 

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

}

  例子中,對象a與b分辨是基類和衍生類別的對象,而函數test的形參卻只是Vehicle類的引用,按照類繼承的特點,系
統把Car類對象看做是一個Vehicle類對象,因為Car類的覆蓋範圍包含Vehicle類,所以test函數的定義並沒有錯誤,我們想利用test
函數達到的目的是,傳遞不同類對象的引用,分別調用不同類的,重載了的,ShowMember成員函數,但是程式的運行結果卻出乎人們的意料,系統分不清楚傳遞過來的
基類對象還是衍生類別對象
,無論是基類對象還是衍生類別對象調用的都是基類的ShowMember成員函數。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.