7-10 用虚函数计算各种图形的面积 (10 分)
定义抽象基类Shape,由它派生出五个派生类:Circle(圆形)、Square(正方形)、Rectangle( 长方形)、Trapezoid (梯形)和Triangle (三角形),用虚函数分别计算各种图形的面积,输出它们的面积和。要求用基类指针数组,每一个数组元素指向一个派生类的对象。PI=3.14159f,单精度浮点数计算。
输入在一行中,给出9个大于0的数,用空格分隔,分别代表圆的半径,正方形的边长,矩形的宽和高,梯形的上底、下底和高,三角形的底和高。
输出所有图形的面积和,小数点后保留3位有效数字。
12.6 3.5 4.5 8.4 2.0 4.5 3.2 4.5 8.4
578.109
代码如下:
#include
using namespace std;
class Shape{
public :
virtual float getArea(){
return 0;
}
};
class Circle:public Shape{
private :
float radius;
public :
Circle(float a):radius(a){
}
float getArea(){
return radius*radius*3.14159f;
}
};
class Square:public Shape{
private :
float len;
public :
Square(float a):len(a){
}
float getArea(){
return len*len;
}
};
class Trapezoid :public Shape{
private:
float up,down,height;
public :
Trapezoid(float a,float b,float c):up(a),down(b),height(c){
}
float getArea(){
return (up+down)*height/2;
}
};
class Rectangle:public Shape{
private :
float width,height;
public :
Rectangle(float a,float b):width(a),height(b){
}
float getArea(){
return width*height;
}
};
class Triangle:public Shape{
private :
float height,down;
public :
Triangle(float a,float b):down(a),height(b){
}
float getArea(){
return height*down/2;
}
};
int main(){
float a,b,c,d,e,f,g,h,i;
scanf("%f %f %f %f %f %f %f %f %f",&a,&b,&c,&d,&e,&f,&g,&h,&i);
Shape *array[5];//新建一个指针数组
Circle c1(a);array[0]=&c1;//取内容传入
Square s(b);array[1]=&s;
Rectangle r(c,d);array[2]=&r;
Trapezoid t(e,f,g);array[3]=&t;
Triangle tr(h,i);array[4]=&tr;
float sum=0;
for(int j=0;j<5;j++)
sum+=array[j]->getArea();//不能是array[j].getArea()否则会报错
printf("%0.3f",sum);
}
这个错误需要注意。
谷雨忍住没上网查,果然自己写才是最有成就感的事情。