11-C. 求最大面积(虚函数和多态)

11-虚函数与多态-
题目描述
请编写程序,从图形数组中找出最大面积。基类框架如下所示:

class Geometry{

public:

virtual double getArea()=0; //计算面积,结果保留小数点后两位

};

以Geometry为基类,构建出Rect(矩形,数据成员为长和宽)和Circle(圆,数据成员为半径)两个类,重写getArea()方法,其他方法根据需要自拟。

写一个TotalArea类,该类结构如下:

class TotalArea{

public:

static void computerTotalArea(Geometry** t,int n);//t为基类二级指针,指向一个基类动态数组,数组的每个元素指向一个子类图形,n为数组的大小

};

生成上述四个类并编写主函数,结果保留两位小数。

输入
第一行表示测试次数。从第二行开始,每个测试用例占一行,每行数据意义如下:图形类型(1为Rect(矩形),2为Circle(圆))、基本信息(Rect是长和宽,Circle是半径)。

输出
最大图形的面积

输入样例
3
1 3 4
2 5
2 6

最大面积=113.04

#include<iostream>
#include<iomanip>
using namespace std;

class geometry
{
    public:
        virtual double getarea()=0;
};

class rect:public geometry
{
    double length,width;
    public:
        rect(double l,double w):length(l),width(w){}
        double getarea()
        {
            return length*width;
        }
};

class circle:public geometry
{
    double radius;
    public:
        circle(double r):radius(r){}
        double getarea()
        {
            return 3.14*radius*radius;
        }
};

class totalarea
{
    static double max;
    public:
        static void computertotalarea(geometry **t,int n)
        {
            for(int i=0;i<n;i++)
                if(t[i]->getarea()>max)
                    max=t[i]->getarea();
        }
        void print()
        {
            cout<<"最大面积="<<fixed<<setprecision(2)<<max<<endl;
        }
};

double totalarea::max=0;

int main()
{
    int t,i,type;
    double length,width,radius;
    cin>>t;
    
    geometry **g=new geometry *[t];
    totalarea T;
        
    for(i=0;i<t;i++)
    {
        cin>>type;
        if(type==1)
        {
            cin>>length>>width;
            g[i]=new rect(length,width);
        }
        else if(type==2)
        {
            cin>>radius;
            g[i]=new circle(radius);
        }
    }
    T.computertotalarea(g,t);
    T.print();
    
    for(i=0;i<t;i++)
        delete g[i];
    delete []g;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值