接口描述了C ++类的行为或功能,而无需承诺该类的特定实现。
C ++接口是使用抽象类实现的,这些抽象类不应与数据抽象混淆,数据抽象是一种将实现细节与关联数据分开的概念。
通过将至少一个函数声明为纯虚函数,可以使一个类抽象。通过在声明中放置“ = 0”来指定纯虚函数,如下所示:
class Box { public: //纯虚函数 virtual double getVolume() = 0; private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box };
一个的目的抽象类(通常被称为ABC)是提供一个适当的基类其他类可以继承。抽象类不能用于实例化对象,而只能用作接口。尝试实例化抽象类的对象会导致编译错误。
因此,如果需要实例化ABC的子类,则它必须实现每个虚函数,这意味着它支持ABC声明的接口。未能在派生类中重写纯虚函数,然后尝试实例化该类的对象,则是编译错误。
可以用来实例化对象的类称为具体类。
请看以下示例,其中父类提供了到基类的接口,以实现名为getArea()的函数-
#include <iostream> using namespace std; class Shape { // Base class public: //纯虚函数 providing interface framework. 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 { // Derived classes 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
您可以看到抽象类如何根据来定义接口,getArea()
而其他两个类如何实现相同的功能,但是使用不同的算法来计算特定于形状的面积。
面向对象的系统可能会使用抽象基类来提供适用于所有外部应用程序的通用标准化接口。然后,通过从该抽象基类继承,可以形成操作类似的派生类。
外部应用程序提供的功能(即公共功能)在抽象基类中作为纯虚拟功能提供。这些纯虚函数的实现在对应于应用程序特定类型的派生类中提供。
即使定义了系统,该体系结构也允许将新的应用程序轻松添加到系统中。