【id:264】【9分】G. 求最大面积(虚函数和多态)
时间限制
1s
内存限制
128MB
题目描述
请编写程序,从图形数组中找出最大面积。基类框架如下所示:
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是半径)。
输出
最大图形的面积
样例查看模式
正常显示
查看格式
输入样例1 <-复制
3
1 3 4
2 5
2 6
输出样例1
最大面积=113.04
要进行向上转型,需要构造基类数组对象时,格式如下:
Geometry **geometry = new Geometry *[times];
为指针的一维数组
#include<iostream>
#include<string>
#include<cstring>
#include <iomanip>
#define PI 3.14
using namespace std;
class Geometry {
public:
Geometry() {}
virtual double getArea() = 0; //计算面积,结果保留小数点后两位
};
// 以Geometry为基类,构建出 Rect(矩形,数据成员为长和宽)和 Circle (圆,数据成员为半径)两个类,重写getArea()方法,其他方法根据需要自拟。
// 写一个TotalArea类,该类结构如下:
class TotalArea {
public:
//t为基类二级指针,指向一个基类动态数组,数组的每个元素指向一个子类图形,n为数组的大小
static void computerMaxArea(Geometry **t, int n);
};
void TotalArea::computerMaxArea(Geometry **t, int n) {
double mm = 0;
for (int i = 0; i < n; ++i) {
// cout << t[i]->getArea() << endl;
if (t[i]->getArea() > mm) {
mm = t[i]->getArea();
}
}
// cout << "66" << endl;
cout << "最大面积=" <<fixed<<setprecision(2)<< mm;
}
class Rect : virtual public Geometry {
public:
int one, two;
Rect(int one, int two) : one(one), two(two) {}
virtual double getArea() {
return one * two;
}
};
class Circle : virtual public Geometry {
public:
int r;
explicit Circle(int r) : r(r) {}
virtual double getArea() {
return r * r * PI;
}
};
int main() {
int times;
cin >> times;
Geometry **geometry = new Geometry *[times];
for (int i = 0; i < times; ++i) {
int type;
cin >> type;
switch (type) {
case 1: {
int one, two;
cin >> one >> two;
geometry[i] = new Rect(one, two);
break;
}
case 2: {
int r;
cin >> r;
geometry[i] = new Circle(r);
break;
}
}
}
TotalArea::computerMaxArea(geometry, times);
}