虚函数求面积

include<iostream>
#include<vector>
#include<iomanip>
#include<cmath>
using namespace std;
const double PI=3.1416;
class Shape{
public:
    virtual ~Shape(){}
    virtual double GetArea() const = 0;
};
class Circle:public Shape{
private:
    double R;
public:
    Circle(double r):R(r){}
    double GetArea()const{return PI*R*R;}
};
class Rectangle:public Shape{
private:
    double Length,Weth;
public:
    Rectangle(double L,double W):Length(L),Weth(W){}
    double GetArea()const {return Length*Weth;}
};
class Triangle:public Shape{
private:
    double a,b,c;
public:
    Triangle(double A,double B,double C):a(A),b(B),c(C){}
    double GetArea()const {return 0.25*sqrt((a+b+c)*(a+b-c)*(a+c-b)*(b+c-a));}
};
double TotalArea (vector<Shape *> &A)
{
    double total=0;
    for(int i=0;i<A.size();i++)
    {
        total=total+A[i]->GetArea();
    }
    return total;
}
int main()
{
    vector<Shape*> A;
    string S;
    double a,b,c,totalarea;
    while(cin>>S){
        if(S=="circle")
        {
            Shape *p;
            cin>>a;
            p=new Circle(a);
            A.push_back(p);
        }
        if(S=="rectangle")
        {
            Shape *p;
            cin>>a>>b;
            p=new Rectangle(a,b);
            A.push_back(p);
        }
        if(S=="triangle")
        {
            Shape *p;
            cin>>a>>b>>c;
            p=new Triangle (a,b,c);
            A.push_back(p);
        }
    }
    totalarea=TotalArea(A);
    cout<<setiosflags(ios::fixed)<<setprecision(4);
    cout<<totalarea<<endl;
    for(int i=0;i<A.size();i++)
    {
        delete A[i];
    }
    return 0;
}
上一篇:NOIP 模拟 $26\; \rm 降雷皇$


下一篇:第八章 排序算法