关闭

OJ嘻唰唰虚函数-计算图形面积

296人阅读 评论(0) 收藏 举报

Description

编写一个程序,定义抽象基类Shape,由它派生出5个派生类: Circle(圆形)、Square(正方形)、Rectangle(矩形)、Trapezoid(梯形)、Triangle(三角形)。
用虚函数分别计算几种图形面积,并求它们之和。
要求用基类指针数组,使它每一个元素指向一个派生类对象。 

Input

圆的半径
正方形的边长
矩形的边长
梯形的上底和下底,高
三角形的底与高

Output

所有图形面积之和(结果保留两位小数)

Sample Input

12.6
3.5
4.5 8.4
2.0 4.5 3.2
4.5 8.4

Sample Output

total of all areas=574.11

 

 

代码:

#include <iostream>
#include <iomanip>
using namespace std;
class  Shape
{
public:
    virtual double area()=0;
};
class Circle:public Shape
{
public:
    Circle(double r=0):radius(r){}
    double area()
    {
        return 3.1415926*radius*radius;
    }
protected:
    double radius;
};
class Square:public Shape
{
public:
    Square(double l=0):longth(l){}
    double area()
    {
       return longth*longth;
    }
protected:
    double longth;
};
class Rectangle:public Shape
{
public:
    Rectangle(double w=0,double h=0):width(w),height(h){}
    double area()
    {
        return width*height;
    }
protected:
    double width;
    double height;
};
class Trapezoid:public Shape
{
public:
    Trapezoid(double s=0,double x=0,double g=0):shang(s),xia(x),gao(g){}
    double area()
    {
        return (shang+xia)*gao/2;
    }
protected:
    double shang;
    double xia;
    double gao;
};
class Triangle:public Shape
{
public:
    Triangle(double b=0,double h=0):base(b),height(h){}
   double area()
    {
        return base*height/2;
    }
protected:
    double base;
    double height;
};

int main()


{


    float r,a,b,w1,w2,w,h;


    cout<<fixed<<setprecision(2);


    cin>>r;


    Circle circle(r);


    cin>>a;


    Square square(a);


    cin>>a>>b;


    Rectangle rectangle(a,b);


    cin>>w1>>w2>>h;


    Trapezoid trapezoid(w1,w1,h);


    cin>>w>>h;


    Triangle triangle(w,h);


    Shape *pt[5]= {&circle,&square,&rectangle,&trapezoid,&triangle};


    double areas=0.0;


    for(int i=0; i<5; i++)


        areas=areas+pt[i]->area();


    cout<<"total of all areas="<<areas<<endl;


    return 0;


}


运行结果:

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:97126次
    • 积分:4153
    • 等级:
    • 排名:第7693名
    • 原创:323篇
    • 转载:0篇
    • 译文:0篇
    • 评论:76条
    文章分类
    最新评论