A. 图形面积(虚函数与多态)
题目描述
编写一个程序,定义抽象基类Shape,在Shape类中定义虚函数area();由它派生出3个派生类:Circle(圆形)、Square(正方形)、Rectangle(矩形)。用虚函数分别计算几种图形面积。
1、要求输出结果保留两位小数。
2、要求用基类指针数组,使它每一个元素指向每一个派生类对象。
输入
测试数据的组数 t
第一组测试数据中圆的半径
第一组测测试数据中正方形的边长
第一组测试数据中矩形的长、宽
.......
第 t 组测试数据中圆的半径
第 t 组测测试数据中正方形的边长
第 t 组测试数据中矩形的长、宽
输出
第一组数据中圆的面积
第一组数据中正方形的面积
第一组数据中矩形的面积
......
第 t 组数据中圆的面积
第 t 组数据中正方形的面积
第 t 组数据中矩形的面积
输入样例1
2
1.2
2.3
1.2 2.3
2.1
3.2
1.23 2.12
输出样例14.52
5.29
2.76
13.85
10.24
2.61
#include<iostream> #include<string> #include <iomanip> using namespace std; class shape { public: virtual void area() { } }; class Circle :public shape { protected: float r; public: Circle(float rr) :r(rr) { } void area() { float area = 3.14 * r * r; cout << fixed << setprecision(2) << area << endl; } }; class square :public shape { protected: float x; public: square(float xx) :x(xx) { } void area() { float area = x * x; cout << fixed << setprecision(2) << area << endl; } }; class rectangle :public shape { protected: float chang, kuan; public: rectangle(float c, float k) :chang(c), kuan(k) { } void area() { float area = chang * kuan; cout << fixed << setprecision(2) << area << endl; } }; int main() { int t; cin >> t; float r, x, chang, kuan; while (t--) { shape* p[3]; cin >> r; p[0] = new Circle(r); cin >> x; p[1] = new square(x); cin >> chang >> kuan; p[2] = new rectangle(chang, kuan); for (int i = 0; i < 3; i++) { p[i]->area(); } } }
B. 汽车收费(虚函数和多态)
现在要开发一个系统,实现对多种汽车的收费工作。 汽车基类框架如下所示:
class Vehicle { protected: string no; //编号 public: virtual void display()=0; //应收费用 }
以Vehicle为基类,构建出Car、Truck和Bus三个类。
Car的收费公式为: 载客数*8+重量*2
Truck的收费公式为:重量*5
Bus的收费公式为: 载客数*30
生成上述类并编写主函数,要求主函数中有一个基类指针Vehicle *pv;用来做测试用。
主函数根据输入的信息,相应建立Car,Truck或Bus类对象,