多型性是物件導向程式設計的乙個重要特徵。c++
支援多型性,在
c++程式設計中能夠實現多型性。 (1
)乙個典型的例子:先建立乙個
point
(點)類,包含資料成員x,
y(座標點),以他為基類,派生出乙個
circle
(圓)類,增減資料成員
r(半徑),再以
circle
類為直接基類,派生出乙個
cylinder
(圓柱體)類,在增加資料成員
h(高)。要求編寫程式,過載運算子「
<<
」和「>>
」,使之能用於輸出以上類物件。
#include using namespace std;
class point
float gety()const
friend ostream &operator<<(ostream&,const point &);
protected:
float x,y;
};point :: point(float a,float b)
void point::setpoint(float a,float b)
ostream&operator<<(ostream&output,const point &p)
float gety()const
friend ostream &operator<<(ostream&,const point &);//過載運算子「<<」
protected:
float x,y;
};point :: point(float a,float b)
void point::setpoint(float a,float b)
ostream&operator<<(ostream&output,const point &p)
float gety()const
friend ostream &operator<<(ostream&,const point &);//過載運算子「<<」
protected:
float x,y;
};point :: point(float a,float b)
void point::setpoint(float a,float b)
ostream&operator<<(ostream&output,const point &p)
virtual float volume()const //ð麯êý
virtual void shapename()const =0 ; //´¿ð麯êý
};class point :public shape
float gety()const
virtual void shapename()const
friend ostream &operator <<(ostream &,const point &);
protected:
float x,y;
};point ::point(float a,float b)
void point ::setpoint(float a,float b)
ostream &operator <<(ostream &output,const point &p)
多型性和虛函式
11.27 多型指的是同樣的資訊被不同型別的物件接收導致不同的行為,包括 靜態多型性和動態多型性。靜態多型性包括 函式過載和運算子過載 動態多型主要 由虛函式實現。虛函式宣告 virsual 型別說明符 函式名 參數列 純虛函式 virtual 函式型別 函式名 參數列 0 在派生類中定義 抽象類 ...
多型性和虛函式
1 向上型別轉換 取乙個物件的位址並將其作為基類的物件來使用 2 函式體和函式呼叫相聯絡稱為 遭 在程式執行之前 晚 在程式執行時 3 虛函式 為了引起晚 需要在基類使用vitual修飾函式 4 c 如何實現晚 vtable 編譯器放置特定的虛函式位址 在每個虛函式類中,編譯器秘密的放置乙個指標。指...
多型性和虛函式
目錄 什麼是多型性 乙個典型的例子 利用虛函式實現動態多型性 虛函式的作用 靜態關聯和動態關聯 什麼情況下應當宣告虛函式 虛析構函式 純虛函式與抽象類 純虛函式 抽象類乙個綜合的例子 向不同的物件傳送同乙個訊息,不同的物件在接收時會產生不同的行為 即方法 從系統實現的角度來看,總共分為兩類 靜態多型...