嘔心瀝血的檔案 學習總結
阿新 • • 發佈:2021-12-17
一、多型
1.多型是指:呼叫成員函式時,會根據呼叫函式的物件的型別來執行不同的函式
2.用到多型的情況:當類之間是通過繼承關聯時
舉例:
#include <iostream> using namespace std; class Shape { protected: int width, height; public: Shape( int a=0, int b=0) { width = a; height = b; } virtual int area() { cout<< "Parent class area :" <<endl; return 0; } }; class Rectangle: public Shape{ public: Rectangle( int a=0, int b=0):Shape(a, b) { } int area () { cout << "Rectangle class area :" <<endl; return (width * height); } };class Triangle: public Shape{ public: Triangle( int a=0, int b=0):Shape(a, b) { } int area () { cout << "Triangle class area :" <<endl; return (width * height / 2); } }; // 程式的主函式 int main( ) { Shape *shape; Rectangle rec(10,7); Triangle tri(10,5); // 儲存矩形的地址 shape = &rec; // 呼叫矩形的求面積函式 area shape->area(); // 儲存三角形的地址 shape = &tri; // 呼叫三角形的求面積函式 area shape->area(); return 0; }
當編譯和執行前面的例項程式碼時,它會產生以下結果:
Rectangle class area :
Triangle class area :
二、虛擬函式
1.定義
虛擬函式是在基類中使用關鍵字virtual宣告的函式
2.作用
在派生類中重新定義基類中定義的虛擬函式時,會告訴編譯器不要靜態連結到該函式
3.靜態多型、動態多型
我們想要的是在程式中任意點可以根據所呼叫的物件型別來選擇呼叫的函式,這種操作被稱為動態連結,或後期繫結;
當呼叫函式被編譯器設定為基類中的版本,就是所謂的靜態多型,或靜態連結,函式呼叫在程式執行前就準備好了
例如,在上例中,如果將 shape 類中的 virtual 去掉
它會產生下列結果:
Parent class area :
Parent class area :
即為,靜態多型。