介面描述類別的行為與功能,不提供具體實作。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;
}
面向物件系統使用抽象基類為外部應用提供標準化介面。衍生類別繼承基類,在對應的派生類中實作純虛擬函式。此架構讓新應用程式易於加入系統,即使系統已定義完成。