概念
C++接口(抽象类)是一种将函数方法和具体实现细节拆离开的概念。现有的接口都使用接口类,跟数据抽象互不混淆,把实现细节和相关数据分离开来。
设计抽象类的目的,是给其他类提供一个可以继承的适当的基类,能够有效管理项目架构,方便继承类实现同一方法的不同应用形式。
经典实例
#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;
}
调试编译后,执行结果: