程序接口

面向对象通过解耦实现,为外部对象提供提供一个适当,通用,标准化的接口,派生类通过继承抽象基类,就把通用规范都继承下来

本质还是抽象-封装-分离-独立程序之间整合思想

  • 解耦是目的, 而程序封装和程序接口是必要手段
  • 接口为程序层序提供核心特性重写,模式如果你规范于XX接口……则必须能……
  • 接口为程序层序提供独立并行开发,只需考虑协议,设计合理,自成体系的接口多实现
/* C++:抽象(接口)类 */
#include <iostream>
using namespace std;
 
// 基类
class Shape 
{
public:
   // 提供接口框架的纯虚函数
   virtual int getArea() = 0;
  public:
   void setWidth(int w)
   {
      width = w;
   }
   void setHeight(int h)
   {
      height = h;
   }
protected: //程序封装
   int width;
   int height;
};
 
// 派生类
class Rectangle: public Shape
{
public:
   int getArea() //接口实现1
   { 
      return (width * height); 
   }
};
class Triangle: public Shape
{
public:
   int getArea() //接口实现2
   { 
      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;
}
  • 定义一个纯虚函数,不代表函数被实现的函数
  • 定义他为虚函数是为了允许用基类的指针来调用子类的这个函数重写
  • 定义一个纯虚函数,才代表函数还没有被实现
  • 定义纯虚函数是为了实现一个接口,起到一个规范的作用,规范继承这个类的程序必须实现这个函数
posted @ 2025-01-23 22:18  NAGISB  阅读(17)  评论(0)    收藏  举报