其他分享
首页 > 其他分享> > 虚函数求面积

虚函数求面积

作者:互联网

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;
}

标签:const,函数,GetArea,double,面积,Shape,return,public
来源: https://blog.csdn.net/weixin_43894901/article/details/94868342