一、问题描述:
定义抽象基类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
二、设计思路:
- 设计基类Shape;
- 设计5个派生类;
- 主函数创建指针数组,指向派生类;
- 输入数据;
- 输出结果;
- 删除动态分配数组。
三、流程图:
四、伪代码实现:
//基类Shape virtual area() = 0 virtual ~Shape() //派生类Circle PI <-3.1415926 area为PI*r*r //正方形 area为a*a//a为边长 //长方形 area为width * height //梯形 area为(topline + baseline) * height / 2 //三角形 area为base * height / 2 //主函数 Shape* shapes[5] shapes[0] = new Circle(r) shapes[1] = new Square(a) shapes[2] = new Rectangle(w, h1) shapes[3] = new Trapezoid(tl, bl, h2) shapes[4] = new Triangle(b, h3) total<-0; for i=0 to 4 do total += shapes[i]->area() end for i=0 to 4 do delete shapes[i]
五、代码实现:
1 #include <iostream> 2 using namespace std; 3 4 class Shape 5 { 6 public: 7 virtual double area() = 0; 8 virtual ~Shape(){} 9 }; 10 //派生类 11 class Circle:public Shape//圆形 12 { 13 private: 14 double r;//半径 15 public: 16 Circle(double _r):r(_r){} 17 const double PI = 3.1415926; 18 double area() 19 { 20 return PI * r * r; 21 } 22 ~Circle(){} 23 }; 24 class Square:public Shape//正方形 25 { 26 private: 27 double a;//边长 28 public: 29 Square(double _a):a(_a){} 30 double area() 31 { 32 return a * a; 33 } 34 ~Square(){} 35 }; 36 class Rectangle:public Shape//长方形 37 { 38 private: 39 double width, height; 40 public: 41 Rectangle(double w,double h):width(w),height(h){} 42 double area() 43 { 44 return width * height; 45 } 46 ~Rectangle(){} 47 }; 48 class Trapezoid:public Shape//梯形 49 { 50 private: 51 double topline, baseline, height; 52 public: 53 Trapezoid(double t,double b,double h):topline(t),baseline(b),height(h){} 54 double area() 55 { 56 return (topline + baseline) * height / 2; 57 } 58 ~Trapezoid(){} 59 }; 60 class Triangle:public Shape//三角形 61 { 62 private: 63 double base, height; 64 public: 65 Triangle(double b,double h):base(b),height(h){} 66 double area() 67 { 68 return base * height / 2; 69 } 70 ~Triangle(){} 71 }; 72 73 int main() 74 { 75 Shape* shapes[5]; 76 double r;//圆的半径 77 double a;//正方形的边长 78 double w, h1;//矩形的宽和高 79 double tl, bl, h2;//梯形的上底下底和高 80 double b, h3;//三角形的底和高 81 cin >> r; 82 cin >> a; 83 cin >> w >> h1; 84 cin >> tl >> bl >> h2; 85 cin >> b >> h3; 86 shapes[0] = new Circle(r); 87 shapes[1] = new Square(a); 88 shapes[2] = new Rectangle(w, h1); 89 shapes[3] = new Trapezoid(tl, bl, h2); 90 shapes[4] = new Triangle(b, h3); 91 double total=0; 92 for (int i = 0; i < 5; i++) 93 { 94 total += shapes[i]->area(); 95 } 96 printf("total of all areas = %.3lf", total); 97 for (int i = 0; i < 5; i++) 98 { 99 delete shapes[i]; 100 } 101 return 0; 102 }
标签:函数,area,double,height,shapes,Shape,计算,图形,public From: https://www.cnblogs.com/tljx-cen/p/17331025.html