虚函数计算各种图形面积

发布时间 2023-04-21 11:21:38作者: 刘冰宇

定义抽象基类Shape,由它派生出五个派生类:Circle(圆形)、Square(正方形)、Rectangle( 长方形)、Trapezoid (梯形)和Triangle (三角形),用虚函数分别计算各种图形的面积,并求出它们的和。要求用基类指针数组。使它的每一个元素指向一个派生类的对象。PI=3.1415926

输入格式:

请在这里写输入格式。例如:输入在一行中给出9个大于0的数,用空格分隔,分别代表圆的半径,正方形的边长,矩形的宽和高,梯形的上底、下底和高,三角形的底和高。

输出格式:

请在这里描述输出格式。例如:输出所有图形的面积和,小数点后保留3位有效数字。

输入样例:

在这里给出一组输入。例如:

12.6 3.5 4.5 8.4 2.0 4.5 3.2 4.5 8.4
 

输出样例:

在这里给出相应的输出。例如:

total of all areas = 578.109
  1 #include<iostream>
  2 using namespace std;
  3 
  4 class Shape
  5 {
  6  public:
  7   virtual double area() const=0;
  8 };
  9 
 10 class Circle:public Shape
 11 {
 12  public:
 13   Circle(double r):radius(r)
 14   {
 15    
 16   }
 17   virtual double area() const
 18   {
 19    return 3.14159*radius*radius;
 20   }
 21  protected:
 22   double radius;
 23 };
 24 
 25 class Square:public Shape
 26 {
 27  public:
 28   Square(double s):side(s)
 29   {
 30    
 31   }
 32   virtual double area() const
 33   {
 34    return side*side;
 35   }
 36  protected:
 37   double side;
 38 };
 39 
 40 class Rectangle:public Shape
 41 {
 42  public:
 43   Rectangle(double w,double h):width(w),height(h)
 44   {
 45    
 46   }
 47   virtual double area() const
 48   {
 49    return width*height;
 50   }
 51  protected:
 52   double width,height; 
 53 };
 54 
 55 class Trapezoid:public Shape
 56 {
 57  public:
 58   Trapezoid(double t,double b,double h):top(t),bottom(b),height(h)
 59   {
 60    
 61   }
 62   virtual double area() const
 63   {
 64    return 0.5*(top+bottom)*height;
 65   }
 66  protected:
 67   double top,bottom,height;
 68   
 69 };
 70 
 71 class Triangle:public Shape
 72 {
 73  public:
 74   Triangle(double w,double h):width(w),height(h)
 75   {
 76    
 77   }
 78   virtual double area() const
 79   {
 80    return 0.5*width*height;
 81   }
 82  protected:
 83   double width,height;
 84 };
 85 
 86 int main()
 87 {
 88  Circle circle(12.6);
 89  Square square(3.5);
 90  Rectangle rectangle(4.5,8.4);
 91  Trapezoid trapezoid(2.0,4.5,3.2);
 92  Triangle triangle(4.5,8.4);
 93  Shape *pt[5]=
 94  {
 95   &circle,&square,&rectangle,&trapezoid,&triangle
 96  };
 97  double areas=0.0;
 98  for(int i=0;i<5;i++)
 99  {
100   areas=areas+pt[i]->area(); 
101  }
102  cout<<"total of all areas = "<<areas<<endl;
103  return 0;
104 }