求最大面积(虚函数和多态)
题目描述
请编写程序,从图形数组中找出最大面积。基类框架如下所示:
class Geometry{
public:
virtual double getArea()=0; //计算面积,结果保留小数点后两位
};
以Geometry为基类,构建出Rect(矩形,数据成员为长和宽)和Circle(圆,数据成员为半径)两个类,重写getArea()方法,其他方法根据需要自拟。
写一个TotalArea类,该类结构如下:
class TotalArea{
public:
static void computerMaxArea(Geometry** t,int n);//t为基类二级指针,指向一个基类动态数组,数组的每个元素指向一个子类图形,n为数组的大小
};
生成上述四个类并编写主函数,结果保留两位小数。
输入
第一行表示测试次数。从第二行开始,每个测试用例占一行,每行数据意义如下:图形类型(1为Rect(矩形),2为Circle(圆))、基本信息(Rect是长和宽,Circle是半径)。
输出
最大图形的面积
示例输入
3
1 3 4
2 5
2 6
示例输出
最大面积=113.04
#include<iostream>
using namespace std;
#include<string>
#include<iomanip>
class Geometry{
public:
Geometry()
{
}
virtual double getArea()=0;
protected:
};
class Rect:public Geometry{
public:
Rect(double length1,double width1)
{
length=length1;
width=width1;
}
virtual double getArea()
{
double area;
area=length*width;
return area;
}
protected:
double length;
double width;
};
class Circle:public Geometry{
public:
Circle(double radius1)
{
radius=radius1;
}
virtual double getArea()
{
double area;
area=3.14*radius*radius;
return area;
}
protected:
double radius;
};
class TotalArea{
public:
TotalArea()
{
}
static void computerMaxArea(Geometry **t,int n)
{
int i;
for(i=0;i<n;i++)
{
if(t[i]->getArea()>max)
max=t[i]->getArea();
}
}
void show()
{
cout<<"最大面积="<<fixed<<setprecision(2)<<max<<endl;
}
protected:
static double max;
};
double TotalArea::max=0;
int main()
{
int i,t;
cin>>t;
int type;
double length1,width1;
double radius1;
Geometry **Geometry1=new Geometry*[t];
for(i=0;i<t;i++)
{
cin>>type;
if(type==1)
{
cin>>length1>>width1;
Geometry1[i]=new Rect(length1,width1);
}
else if(type==2)
{
cin>>radius1;
Geometry1[i]=new Circle(radius1);
}
}
TotalArea TotalArea1;
TotalArea1.computerMaxArea(Geometry1,t);
TotalArea1.show();
for(i=0;i<t;i++)
delete Geometry1[i];
delete []Geometry1;
return 0;
}