正在閱讀:C++中類的多態(tài)與虛函數(shù)的使用C++中類的多態(tài)與虛函數(shù)的使用

2005-03-16 10:18 出處:PConline 作者:管寧 責任編輯:xietaoming

 

  類的多態(tài)特性是支持面向對象的語言最主要的特性,有過非面向對象語言開發(fā)經(jīng)歷的人,通常對這一章節(jié)的內容會覺得不習慣,因為很多人錯誤的認為,支持類的封裝的語言就是支持面向對象的,其實不然,Visual BASIC 6.0 是典型的非面向對象的開發(fā)語言,但是它的確是支持類,支持類并不能說明就是支持面向對象,能夠解決多態(tài)問題的語言,才是真正支持面向對象的開發(fā)的語言,所以務必提醒有過其它非面向對象語言基礎的讀者注意!

  多態(tài)的這個概念稍微有點模糊,如果想在一開始就想用清晰用語言描述它,讓讀者能夠明白,似乎不太現(xiàn)實,所以我們先看如下代碼:

//例程1 
#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 main()   
{   
    Vehicle a(120,4); 
    a.ShowMember(); 
    Car b(180,110,4); 
    b.ShowMember(); 
    cin.get(); 
}

  在c++中是允許派生類重載基類成員函數(shù)的,對于類的重載來說,明確的,不同類的對象,調用其類的成員函數(shù)的時候,系統(tǒng)是知道如何找到其類的同名成員,上面代碼中的a.ShowMember();,即調用的是Vehicle::ShowMember(),b.ShowMember();,即調用的是Car::ShowMemeber();。

鍵盤也能翻頁,試試“← →”鍵
302 Found

302 Found


Powered by Tengine
tengine