C++习题 虚函数-计算图形面积

Problem H: C++习题 虚函数-计算图形面积

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 287   Solved: 226
[ Submit][ Status][ Web Board]

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

HINT

主函数已给定如下,提交时不需要包含,会自动添加到程序尾部

/* C++代码 */


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;

}
 
#include <iostream>
#include <iomanip>
using namespace std;
class Shape
{
public:
    virtual double  area() const=0;
};
class Circle:public Shape
{
private:
    double r;
public:
    Circle():r(0) {}
    Circle(double r1):r(r1) {}
    virtual double area()const
    {
        return 3.1415926*r*r;
    }
};
class Square:public Shape
{
private:
    double a;
public:
    Square():a(0) {}
    Square(double a1):a(a1) {}
    virtual double area()const
    {
        return a*a;
    }
};
class Rectangle:public Shape
{
private:
    double a,b;
public:
    Rectangle():a(0),b(0) {}
    Rectangle(double a1,double b1):a(a1),b(b1) {}
    virtual double area()const
    {
        return a*b;
    }
};
class Trapezoid:public Shape
{
private:
    double a,b,h;
public:
    Trapezoid():a(0),b(0),h(0) {}
    Trapezoid(double a1,double b1,double h1):a(a1),b(b1),h(h1) {}
    virtual double area()const
    {
        return (a+b)*h*0.5;
    }
};
class Triangle:public Shape
{
private:
    double a,b;
public:
    Triangle():a(0),b(0) {}
    Triangle(double a1,double b1):a(a1),b(b1) {}
    virtual double  area()const
    {
        return a*b*0.5;
    }
};

你可能感兴趣的:(类,对象,Class)