為了要解決上述不能正確分辨物件類型的問題,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
關
鍵字,那麼該成員函數就變成了虛函數,從上例代碼啟動並執行結果看,系統成功的分辨出了對象的真實類型,成功的調用了各自的重載成員函數。
多態特性讓程式員省去了細節的考慮,提高了開發效率,使代碼大大的簡化,當然虛函數的定義也是有缺陷的,因為多態特性增加了一些資料存放區和執行指令的開
銷,所以能不用多態最好不用。