定义抽象基类Shape,由它派生出五个派生类:Circle(圆形)、Square(正方形)、Rectangle( 长方形)、Trapezoid (梯形)和Triangle (三角形),用虚函数分别计算各种图形的面积,并求出它们的和。要求用基类指针数组。使它的每一个元素指向一个派生类的对象。
#include <iostream>
using namespace std;
class Shape
{
public:
Shape()
{}
Shape(double s[])
{}
virtual double Area()=0;
};
class Circle:public Shape
{
public:
Circle(double r)
{
this->r=r;
}
double Area()
{
return r*r*3.1415926;
}
private:
double r;
};
class Square:public Shape
{
public:
Square(double a)
{
this->a=a;
}
double Area()
{
return a*a;
}
private:
double a;
};
class Rectangle:public Shape
{
public:
Rectangle(double x,double y)
{
this->x=x;
this->y=y;
}
double Area()
{
return x*y;
}
private:
double x;
double y;
};
class Trapezoid:public Shape
{
public:
Trapezoid(double w,double m,double h)
{
this->w=w;
this->m=m;
this->h=h;
}
double Area()
{
return ((w+m)*h)/2;
}
private:
double w;
double m;
double h;
};
class Triangle:public Shape
{
public:
Triangle(double l,double z)
{
this->l=l;
this->z=z;
}
double Area()
{
return l*z/2;
}
private:
double l;
double z;
};
int main()
{
Shape* shape[5];
double r,a,x,y,w,m,h,l,z;
cin>>r>>a>>x>>y>>w>>m>>h>>l>>z;
shape[0]=new Circle(r);
shape[1]=new Square(a);
shape[2]=new Rectangle(x,y);
shape[3]=new Trapezoid(w,m,h);
shape[4]=new Triangle(l,z);
cout<<"total of all areas = "<<shape[0]->Area()+shape[1]->Area()+shape[2]->Area()+shape[3]->Area()+shape[4]->Area();
return 0;
}