xt12-5.cpp
上传用户:liubin
上传日期:2022-06-13
资源大小:85k
文件大小:3k
源码类别:

书籍源码

开发平台:

Visual C++

  1. #include <iostream>
  2. using namespace std;
  3. //定义抽象基类Shape
  4. class Shape
  5. {public:
  6.  virtual double area() const =0;                                //纯虚函数
  7. };
  8. //定义Circle(圆形)类
  9. class Circle:public Shape
  10. {public:
  11. Circle(double r):radius(r){}                                     //结构函数
  12.   virtual double area() const {return 3.14159*radius*radius;};   //定义虚函数
  13.  protected:
  14.   double radius;                                                 //半径
  15. };
  16. //定义Square(正方形)类
  17. class Square:public Shape
  18. {public:
  19.   Square(double s):side(s){}                                     //结构函数     
  20.   virtual double area() const {return side*side;}                //定义虚函数
  21.  protected:
  22.   double side;
  23. };
  24. //定义Rectangle(矩形)类
  25. class Rectangle:public Shape
  26. {public:
  27.  Rectangle(double w,double h):width(w),height(h){}               //结构函数
  28.  virtual double area() const {return width*height;}              //定义虚函数
  29.  protected:
  30.   double width,height;                                           //宽与高
  31. };
  32. //定义Trapezoid(梯形)类
  33. class Trapezoid:public Shape
  34. {public:
  35.   Trapezoid(double t,double b,double h):top(t),bottom(t),height(h){} //结构函数
  36.   virtual double area() const {return 0.5*(top+bottom)*height;}      //定义虚函数
  37.  protected:
  38.   double top,bottom,height;                                          //上底、下底与高
  39. };
  40. //定义Triangle(三角形)类
  41. class Triangle:public Shape
  42. {public:
  43.   Triangle(double w,double h):width(w),height(h){}                //结构函数
  44.   virtual double area() const {return 0.5*width*height;}          //定义虚函数
  45.  protected:
  46.   double width,height;                                            //宽与高
  47. };
  48. int main()
  49. {
  50.  Circle circle(12.6);                                             //建立Circle类对象circle
  51.  Square square(3.5);                                              //建立Square类对象square
  52.  Rectangle rectangle(4.5,8.4);                                    //建立Rectangle类对象rectangle
  53.  Trapezoid trapezoid(2.0,4.5,3.2);                                //建立Trapezoid类对象trapezoid
  54.  Triangle triangle(4.5,8.4);                                      //建立Triangle类对象
  55.  Shape *pt[5]={&circle,&square,&rectangle,&trapezoid,&triangle};  
  56.                                               //定义基类指针数组pt,使它每一个元素指向一个派生类对象
  57.  double areas=0.0;                                                //areas为总面积
  58.  for(int i=0;i<5;i++)
  59.   {areas=areas+pt[i]->area();}
  60.  cout<<"totol of all areas="<<areas<<endl;   //输出总面积
  61.  return 0;