接口是一系列抽象方法的聲明,是一些方法特徵的集合,這些方法都應該是抽象的,接口描述了類的行爲和功能,而不需要完成類的特定實現。需要由具體的類(實現接口的類)去實現,然後第三方就可以通過這組抽象方法調用,讓具體的類執行具體的方法。
C++ 接口是使用抽象類來實現的,抽象類與數據抽象互不混淆,數據抽象是一個把實現細節與相關的數據分離開的概念。如果類中至少有一個函數被聲明爲純虛函數,則這個類就是抽象類。純虛函數是通過在聲明中使用 "= 0" 來指定的。抽象類如下所示:
class Box
{
public:
// 純虛函數,Box類爲抽象類
virtual double getVolume() = 0;
private:
double length; // 長度
double breadth; // 寬度
double height; // 高度
};
設計抽象類(通常稱爲 ABC)的是爲了給其它類提供一個可以繼承的基類。抽象類不能實例化對象,僅能作爲接口使用。試圖實例化抽象類會導致編譯錯誤。
因此,如果實例化抽象類的子類,則必須實現每個虛函數,這也意味着 C++ 支持使用 ABC 聲明接口。如果沒有在派生類中重載純虛函數,就嘗試實例化該類的對象,會導致編譯錯誤。
如下面的例子,基類 Shape 提供了一個接口 getArea(),在兩個派生類 Rectangle 和 Triangle 中分別實現了 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;
int height;
};
// 派生類
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// 輸出對象的面積
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// 輸出對象的面積
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
運行結果如下:
Total Rectangle area: 35
Total Triangle area: 17