一、问题描述:
定义抽象基类Shape,由它派生出五个派生类:Circle(圆形)、Square(正方形)、Rectangle( 长方形)、Trapezoid (梯形)和Triangle (三角形),用虚函数分别计算各种图形的面积,输出它们的面积和。要求用基类指针数组,每一个数组元素指向一个派生类的对象。PI=3.14159f,单精度浮点数计算。
输入格式:
输入在一行中,给出9个大于0的数,用空格分隔,分别代表圆的半径,正方形的边长,矩形的宽和高,梯形的上底、下底和高,三角形的底和高。
输出格式:
输出所有图形的面积和,小数点后保留3位有效数字。
二、解题思路:
首先,定义一个抽象类作为父类虚函数为计算面积函数,在定义其五个子类,在重新定义计算面积函数,在主函数中,定义一个指针数组,每个指针指向五个子类的地址,最后用父类的指针去调用子类的函数,最后输出其面积的加和。
三、代码实现:
1 #include <iostream> 2 #include<iomanip> 3 using namespace std; 4 class CShape 5 { 6 public: 7 virtual double Area() { }; 8 }; 9 class CRectangle:public CShape 10 { 11 public: 12 double w,h; 13 virtual double Area(){return w * h;} 14 }; 15 class CCircle:public CShape 16 { 17 public: 18 double r; 19 virtual double Area(){return 3.14159 * r * r ;} 20 21 }; 22 class CTriangle:public CShape 23 { 24 public: 25 double a,b; 26 virtual double Area(){ 27 return a*b/2; 28 } 29 }; 30 class Square:public CShape 31 { 32 public: 33 double w; 34 virtual double Area(){return w*w;} 35 }; 36 class Trapezoid:public CShape 37 { 38 public: 39 double d,c,h; 40 virtual double Area(){return (d+c)*h/2.0;} 41 }; 42 CShape *pShapes[100]; 43 int main() 44 { 45 int i; 46 CRectangle *pr; CCircle *pc; CTriangle *pt; 47 Square *ps;Trapezoid *ptt; 48 for( i = 0;i < 5;++i ) { 49 switch(i) { 50 case 0: 51 pc = new CCircle(); 52 cin >> pc->r; 53 pShapes[i] = pc; 54 break; 55 case 1: 56 ps = new Square(); 57 cin >> ps->w; 58 pShapes[i] = ps; 59 break; 60 case 2: 61 pr = new CRectangle(); 62 cin >> pr->w >> pr->h; 63 pShapes[i] = pr; 64 break; 65 case 3: 66 ptt = new Trapezoid(); 67 cin >> ptt->d>> ptt->c>> ptt->h; 68 pShapes[i] = ptt; 69 break; 70 case 4: 71 pt = new CTriangle(); 72 cin >> pt->a >> pt->b; 73 pShapes[i] = pt; 74 break; 75 } 76 } 77 double count=0; 78 for(i = 0;i <5;++i) 79 count+=pShapes[i]->Area(); 80 cout<<fixed<<setprecision(3)<<count; 81 return 0; 82 }
标签:pShapes,Area,double,23,2023.5,CShape,打卡,ptt,public From: https://www.cnblogs.com/lixinyao20223933/p/17426228.html