定义抽象基类Shape,由它派生出3个派生类: Circle(圆形)、Rectangle(矩形)、Tr足毂忍珩iangle(三角形),用一个函数printArea分别输出以上三者的面积,3个图形的数据在定义对象时给定。
#include<iostream> usingnamespacestd; classShape { public:
virtualfloatprintArea()const{return0.0;}; }; classCircle:publicShape {
public: Circle(float=0); virtualfloatprintArea()const{return3.14159*radius*radius;}
protected: floatradius; }; Circle::Circle(floatr):radius(r) { } classRectangle:publicShape { public: Rectangle(float=0,float=0);
virtualfloatprintArea()const; protected: floatheight; floatwidth; };
Rectangle::Rectangle(floatw,floath):width(w),height(h){ }
floatRectangle::printArea()const { returnwidth*height; }
classTriangle:publicShape { public: Triangle(float=0,float=0);
virtualfloatprintArea()const; protected: floatheight; floatwidth;
抽象类(abstract base class,ABC)就是类里定义了纯虚成员函数的类。纯虚函数 只提供了接口,并没有具体实现。抽象类不能被实例化(不能创建对象),通常是作为基类供子类继承,子类中重写虚函数,实现具体的接口。简言之,ABC描述的是至少使用一个纯虚函数的接口,从ABC派生出的类将根据派生类的具体特征,使用常规虚函数来实现这种接口。