程序接口
面向对象通过
解耦实现,为外部对象提供提供一个适当,通用,标准化的接口,派生类通过继承抽象基类,就把通用规范都继承下来本质还是
抽象-封装-分离-独立程序之间整合思想
- 解耦是目的, 而程序
封装和程序接口是必要手段 - 接口为程序层序提供
核心特性重写,模式如果你规范于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;
}
- 定义一个纯虚函数,不代表函数
为不被实现的函数 - 定义他为虚函数是为了允许用基类的指针来调用子类的这个函数
重写 - 定义一个纯虚函数,才代表函数
还没有被实现 - 定义纯虚函数是为了实现一个
接口,起到一个规范的作用,规范继承这个类的程序必须实现这个函数

浙公网安备 33010602011771号