定义抽象基类Shape,由它派生出五个派生类:Circle(圆形)、Square(正方形)、Rectangle( 长方形)、Trapezoid (梯形)和Triangle (三角形),用虚函数分别计算各种图形的面积,并求出它们的和。要求用基类指针数组。使它的每一个元素指向一个派生类的对象。PI=3.1415926。
1 #include <iostream> 2 #define PI 3.1415926 3 using namespace std; 4 class Shape 5 { 6 public: 7 virtual double area()=0; 8 }; 9 class Circle:public Shape 10 { 11 private: 12 double r; 13 public: 14 Circle(double x):r(x){} 15 double area() 16 { 17 return PI*r*r; 18 } 19 }; 20 class Square:public Shape 21 { 22 private: 23 double x; 24 public: 25 Square(double a):x(a){} 26 double area() 27 { 28 return x*x; 29 } 30 }; 31 class Rectangle:public Shape 32 { 33 private: 34 double x; 35 double y; 36 public: 37 Rectangle(double a,double b):x(a),y(b){} 38 double area() 39 { 40 return x*y; 41 } 42 }; 43 class Trapezoid:public Shape 44 { 45 private: 46 double x; 47 double y; 48 double z; 49 public: 50 Trapezoid(double a,double b,double c):x(a),y(b),z(c){} 51 double area() 52 { 53 return (x+y)*z/2; 54 } 55 }; 56 class Triangle:public Shape 57 { 58 private: 59 double x; 60 double y; 61 public: 62 Triangle(double a,double b):x(a),y(b){} 63 double area() 64 { 65 return x*y/2; 66 } 67 }; 68 int main() 69 { 70 Shape* Shapes[5]; 71 double a,b,c,d,e,f,g,h,i; 72 cin>>a>>b>>c>>d>>e>>f>>g>>h>>i; 73 Shapes[0]=new Circle(a); 74 Shapes[1]=new Square(b); 75 Shapes[2]=new Rectangle(c,d); 76 Shapes[3]=new Trapezoid(e,f,g); 77 Shapes[4]=new Triangle(h,i); 78 double sum; 79 sum=Shapes[0]->area()+Shapes[1]->area()+Shapes[2]->area()+Shapes[3]->area()+Shapes[4]->area(); 80 cout<<"total of all areas = "<<sum<<endl; 81 }
标签:练习题,area,double,pta,class,Shapes,Shape,程序设计,public From: https://www.cnblogs.com/Lyh3012648079/p/17324090.html