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

C++ 介面(抽象類別)完整教學:純虛擬函式與設計策略

     編輯:C++ 入門

C++ 介面(抽象類別)

介面描述類別的行為與功能,不提供具體實作。C++ 透過抽象類別實作介面,抽象類別與資料抽象不同——後者是將實作細節與資料分離的概念。

若類別至少有一個純虛擬函式(宣告時使用 = 0),即為抽象類別:

class Box {
public:
    virtual double getVolume() = 0;  // 純虛擬函式
private:
    double length, breadth, height;
};

抽象類別的目的與限制

  • 提供適當的基類供繼承,定義介面契約
  • 無法實例化物件,嘗試會導致編譯錯誤
  • 衍生類別必須實作所有純虛擬函式才能實例化
  • 可實例化的類別稱為具體類別

抽象類別實作範例

基類 Shape 定義介面 getArea(),兩個衍生類別分別實作:

#include <iostream>
using namespace std;

class Shape {
public:
    virtual int getArea() = 0;
    void setWidth(int w) { width = w; }
    void setHeight(int h) { height = h; }
protected:
    int width, height;
};

class Rectangle : public Shape {
public:
    int getArea() { return width * height; }
};

class Triangle : public Shape {
public:
    int getArea() { return (width * height) / 2; }
};

int main() {
    Rectangle rect; rect.setWidth(5); rect.setHeight(7);
    Triangle tri; tri.setWidth(5); tri.setHeight(7);
    cout << "Rectangle area: " << rect.getArea() << endl;  // 35
    cout << "Triangle area: " << tri.getArea() << endl;    // 17
    return 0;
}

設計策略

面向物件系統使用抽象基類為外部應用提供標準化介面。衍生類別繼承基類,在對應的派生類中實作純虛擬函式。此架構讓新應用程式易於加入系統,即使系統已定義完成。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved