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

www.MyException.Cn  网友分享于：2014-06-03  浏览：14次
C++习题 虚函数-计算图形面积

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

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 122  Solved: 86
[Submit][Status][Web Board]

## Sample Input

12.63.54.5 8.42.0 4.5 3.24.5 8.4

## Sample Output

total of all areas=574.11
#include <iostream>
#include<iomanip>
using namespace std;
class Shape
{
public:
virtual float area()=0;
private:

};
class Circle:public Shape
{
public:
Circle(float s)
{r=s;
}
float area(){return (3.1415926*r*r);}
private:
float r;

};

class Square:public Shape
{
public:
Square (float s)
{
a=s;
}
float area() { return (a*a); }
private:
float a;
};
class Rectangle :public Shape
{
public:
Rectangle (float s,float d)
{
a=s;
b=d;
}
float area() { return (a*b);}
private:
float a,b;
};
class Trapezoid:public Shape
{
public:
Trapezoid (float s,float d,float ss)
{
w1=s;
w2=d;
h=ss;
}
float area() { return ((w1+w2)*h/2); }
private:
float w1,w2,h;
};
class Triangle:public Shape
{
public:
Triangle (float s,float d)
{
w=s;
h=d;
}
float area() { return (w*h/2); }
private:
float w,h;
};

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;

}