(1)分析相关对象的需求,设计出一组实现公共功能的函数。
(2)将这些函数作为基类的虚函数(或纯虚函数),它们定义了一个
统一的公共接口。
(3)由该类基类派生出若干子类,在各子类中实现这些虚函数。
#include<iostream> using namespace std; class Container //抽象类 { protected: double radius; public: Container(double radius){ Container::radius = radius; } virtual double surface_area()=0;//纯虚函数 virtual double volume()=0;//纯虚函数 }; class Cube:public Container { public: Cube(double radius):Container(radius){} double surface_area(){return radius*radius*6;} double volume(){return radius*radius*radius;} }; class Sphere:public Container { public: Sphere(double radius):Container(radius){} double surface_area(){return radius*radius*3.14;} double volume(){return 3.1416*radius*radius*radius*4/3;} }; class Cylinder:public Container { double height; public: Cylinder(double radius, double height):Container(radius){ Cylinder::height = height; } double surface_area(){ return 2*3.1416*radius*(height+radius); } double volume(){return 3.1416*radius*radius*height;} }; int main() { Container *p; Cube obj1(5); Sphere obj2(5); Cylinder obj3(5,5); p = &obj1; cout<<"正方体表面积:"<<p->surface_area()<<endl; cout<<"正方体体积:"<<p->volume()<<endl; p = &obj2; cout<<"球体表面积:"<<p->surface_area()<<endl; cout<<"球体体积:"<<p->volume()<<endl; p = &obj2; cout<<"圆柱体表面积:"<<p->surface_area()<<endl; cout<<"圆柱体体积:"<<p->volume()<<endl; return 0; }