一、问题描述。
定义抽象基类Shape,由它派生出五个派生类:Circle(圆形)、Square(正方形)、Rectangle( 长方形)、Trapezoid (梯形)和Triangle (三角形),用虚函数分别计算各种图形的面积,输出它们的面积和。要求用基类指针数组,每一个数组元素指向一个派生类的对象。PI=3.14159f,单精度浮点数计算。
输入格式:
输入在一行中,给出9个大于0的数,用空格分隔,分别代表圆的半径,正方形的边长,矩形的宽和高,梯形的上底、下底和高,三角形的底和高。
输出格式:
输出所有图形的面积和,小数点后保留3位有效数字。
代码实现。
#include<iostream>
#include<iomanip>
using namespace std;
#define pl 3.14159f
class Shape
{
public:
virtual float area() = 0;
};
class Circle :public Shape
{
private:
float r;
public:
Circle(float a){ r = a; }
float area()
{
return r*r*pl;
}
};
class Square:public Shape
{
private:
float a;
public:
Square(float sidea){ a = sidea; }
float area()
{
return a*a;
}
};
class Rectangle:public Shape
{
private:
float a, b;
public:
Rectangle(float sidea, float sideb){ a = sidea; b = sideb; }
float area()
{
return a*b;
}
};
class Trapezoid:public Shape
{
private:
float s, n, h;
public:
Trapezoid(float sides, float siden, float sideh){ s = sides; n = siden; h = sideh; }
float area()
{
return ((s + n)*h) / 2;
}
};
class Triangle:public Shape
{
private:
float s, h;
public:
Triangle(float sides, float x){ s = sides; h = x; }
float area()
{
return (s*h) / 2;
}
};
int main()
{
float a, b, c, d, e, f, g, h, i;
float sum=0;
cin >> a >> b >> c >> d >> e >> f >> g >> h >> i;
Shape*p[5];
Circle c1(a);
p[0] = &c1;
Square s1(b);
p[1] = &s1;
Rectangle r1(c, d);
p[2] = &r1;
Trapezoid t1(e, f, g);
p[3] = &t1;
Triangle t2(h, i);
p[4] = &t2;
for (int j = 0; j < 5; j++)
{
sum = sum + p[j]->area();
}
cout <<fixed<<setprecision(3) <<sum << endl;
}