C ++中的接口(抽象类)

接口描述C ++类的行为或功能,而不提交该类的特定实现.

C ++接口使用抽象类实现并且这些抽象类不应该与数据抽象相混淆,数据抽象是将实现细节与关联数据分开的概念.

通过将其至少一个函数声明为纯虚拟功能.通过在声明中放置"= 0"来指定纯虚函数,如下所示 :

class Box {
   public:
      // pure virtual function
      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;
 
// Base class
class Shape {
   public:
      // pure virtual function providing interface framework.
      virtual int getArea() = 0;
      void setWidth(int w) {
         width = w;
      }
   
      void setHeight(int h) {
         height = h;
      }
   
   protected:
      int width;
      int height;
};
 
// Derived classes
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);
   
   // Print the area of the object.
   cout << "Total Rectangle area: " << Rect.getArea() << endl;

   Tri.setWidth(5);
   Tri.setHeight(7);
   
   // Print the area of the object.
   cout << "Total Triangle area: " << Tri.getArea() << endl; 

   return 0;
}

编译并执行上述代码时,会产生以下结果 :

Total Rectangle area: 35
Total Triangle area: 17

您可以看到如何定义抽象类getArea()方面的接口和另外两个类实现了相同的功能但使用不同的算法来计算特定于形状的区域.

设计策略

面向对象的系统可能使用抽象基类来提供适用于所有外部应用程序的通用标准化接口.然后,通过从该抽象基类的继承,形成类似操作的派生类.

外部应用程序提供的功能(即公共函数)作为纯虚函数提供.抽象基类.这些纯虚函数的实现在派生类中提供,这些派生类对应于应用程序的特定类型.

此体系结构还允许将新应用程序轻松添加到系统中,即使在系统已经定义.