上题目
用虚函数计算各种图形的面积 (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
唠嗑
其实是简单的题。训练一下以增强对“类和对象”知识点的理解。
1.中间遇见报错
“ 1 个无法解析的外部命令 ”
“ undefined reference to `typeinfo for shape'” { return PI * t1 * t1; }{return 0.0;}
为什么呢?因为我在写基类的时候是这么写的
class shape
{
public:
virtual float mian(void);
};
而按理是这样
class shape
{
public:
virtual float mian(void){return 0.0;}
};
上代码
#include <iostream>
using namespace std;
const float PI = 3.14159f;
class shape
{
public:
virtual float mian(void){return 0.0;}
};
class yuan :public shape
{
public:float t1; float t2; float h;
yuan() {
t1 = 0; t2 = 0; h = 0;
}
float mian(void) { return PI * t1 * t1; }
};
class zheng :public shape
{
public: float t1; float t2; float h;
zheng()
{
t1 = 0; t2 = 0; h = 0;
}
float mian(void) { return t1 * t1; }
};
class chang :public shape
{
public:float t1; float t2; float h;
chang()
{
t1 = 0; t2 = 0; h = 0;
}
float mian(void) { return t1 * t2; }
};
class ti :public shape
{
public:float t1; float t2; float h;
ti()
{
t1 = 0; t2 = 0; h = 0;
}
float mian(void) { return (t1 + t2) * h / 2; }
};
class san :public shape
{
public: float t1; float t2; float h;
san()
{
t1 = 0; t2 = 0; h = 0;
}
float mian(void) { return t1 * t2 / 2; }
};
int main()
{
int i; float s=0;
class shape *x[5];
class yuan a; class zheng b; class chang c; class ti d; class san e;
x[0] = &a; x[1] = &b; x[2] = &c; x[3] = &d; x[4] = &e;
cin >> a.t1 >> b.t1 >> c.t1 >>c.t2 >> d.t1 >> d.t2 >> d.h >> e.t1 >> e.t2;
for (i = 0; i < 5; i++)
{
s += x[i]->mian();
}
printf("%.3f", s);
return 0;
}