当你要创建几个类,分别表示矩形,圆形,椭圆形等图形时,每一个类都会去实现获取面积(getArea()),绘制(draw())等通用接口,因此想到了继承。
我们可以定义一个形状类Shape,但是Shape并不是一个实体,仅仅是抽象出来的概念,您也不想去创建Shape的对象,仅仅为了预定义同类的接口而已。
此时就需要用到纯虚函数,Shape也被称为抽象数据类型ADT(Abstract Data Type)。
如果子类继承自ADT类,子类必须实现基类的所有纯虚函数。
class Shape
{
public:
Shape(){};
virtual ~Shape(){};
virtual void draw() = 0; //子类必须实现该方法
virtual void getArea() = 0;//子类必须实现该方法
private:
};
class Rectangle : public Shape
{
public:
Rectangle(){};
~Rectangle(){};
void draw(){ cout << "Rectangle draw..." << endl; }
void getArea(){ cout << "Rectangle getArea..." << endl; }
private:
};
class Circle : public Shape
{
public:
Circle(){};
~Circle(){};
void draw(){ cout << "Circle draw..." << endl; }
void getArea(){ cout << "Circle getArea..." << endl; }
private:
};
int _tmain(int argc, _TCHAR* argv[])
{
//Shape shape;//error 不能对抽象数据类型(ADT)创建实例
Rectangle rectangle;
rectangle.getArea();
}