首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++ 多型:虛擬函式、動態連結與純虛擬函式完整解析

     編輯:C++ 入門

C++ 多型

多型意指多種形態。當類別存在繼承階層時,呼叫成員函式會根據物件實際類型執行不同函式。

靜態多型(早期繫結)問題

未加 virtual 時,編譯器依指標宣告類型決定呼叫基類版本:

class Shape { public: int area() { cout << "Parent class area"; return 0; } };
Shape* shape = &rect; shape->area();  // 輸出 "Parent class area" (錯誤)

此為靜態多型/靜態連結/早期繫結——編譯期決定呼叫目標。

動態多型(晚期繫結)解決

基類函式加 virtual,編譯器依指標實際指向物件決定呼叫:

class Shape { public: virtual int area() { ... } };
// 輸出 "Rectangle class area" → "Triangle class area" (正確)

此為動態連結/晚期繫結——執行期根據物件類型決定。

虛擬函式與純虛擬函式

  • 虛擬函式:基類提供預設實作,衍生類別可選擇性覆寫(virtual int area() { ... })
  • 純虛擬函式:基類不提供實作,強制衍生類別實作(virtual int area() = 0;),構成介面契約

完整範例程式碼

#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; shape->area();  // Rectangle class area
    shape = &tri; shape->area();  // Triangle class area
    return 0;
}

關鍵差異總結

特性非虛擬函式虛擬函式純虛擬函式
繫結時機編譯期 (靜態)執行期 (動態)執行期 (動態)
基類實作必要可選禁止 (=0)
衍生類別覆寫隱藏而非覆寫可選強制
基類可實例化是是否 (抽象類別)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved