声明抽象基类Shape,由它派生出5个派生类;Circle(圆形)、Square(正方形)、Rectangle(矩形)、Trapezoid(梯形)、Triangle(三角形),分别计算几种图形的面积,并求它们的和并显示出来。请按照要求选择如下一种方式编程实现。 注意圆周率取3.14. 实现方式: 1.使用继承和派生完成上述功能。 2.使用动态多态完成上述功能,提示:基类指针+派生类对象。 3. 使用派生类构造函数知识完成上述功能。 4. 作业竞赛要求的其他方式 输入描述 输入圆的半径 输入正方形的边长 输入矩形的长和宽 输入梯形的上底、下底、高 输入三角形的底、高 输出描述 输出每种图形的面积、所有图形面积的总和。每个面积占一行,面积前显示图形名称 样例输入 12.6 3.5 4.5 8.4 2.0 4.5 3.2 4.5 8.4 样例输出 Circle:498.51 Square:12.25 Rectangle:37.80 Trapezoid:10.40 Triangle:18.90 total of all areas=577.86
时间: 2024-03-14 08:42:52 浏览: 18
好的,以下是使用继承和派生完成的代码实现:
```c++
#include <iostream>
using namespace std;
//声明抽象基类Shape
class Shape{
public:
virtual double getArea() = 0; //声明纯虚函数getArea
};
//派生类Circle(圆形)
class Circle:public Shape{
private:
double radius; //圆的半径
public:
Circle(double r):radius(r){} //构造函数
double getArea(){ //实现纯虚函数getArea
return 3.14 * radius * radius;
}
};
//派生类Square(正方形)
class Square:public Shape{
private:
double side; //正方形的边长
public:
Square(double s):side(s){} //构造函数
double getArea(){ //实现纯虚函数getArea
return side * side;
}
};
//派生类Rectangle(矩形)
class Rectangle:public Shape{
private:
double length; //矩形的长
double width; //矩形的宽
public:
Rectangle(double l, double w):length(l),width(w){} //构造函数
double getArea(){ //实现纯虚函数getArea
return length * width;
}
};
//派生类Trapezoid(梯形)
class Trapezoid:public Shape{
private:
double top; //梯形的上底
double bottom; //梯形的下底
double height; //梯形的高
public:
Trapezoid(double t, double b, double h):top(t),bottom(b),height(h){} //构造函数
double getArea(){ //实现纯虚函数getArea
return (top + bottom) * height / 2;
}
};
//派生类Triangle(三角形)
class Triangle:public Shape{
private:
double base; //三角形的底边
double height; //三角形的高
public:
Triangle(double b, double h):base(b),height(h){} //构造函数
double getArea(){ //实现纯虚函数getArea
return base * height / 2;
}
};
int main(){
double r, s, l, w, t, b, h; //定义各图形的参数
cin >> r >> s >> l >> w >> t >> b >> h; //输入各图形的参数
Shape *shape[5]; //定义指针数组
shape[0] = new Circle(r); //创建对象并赋给指针
shape[1] = new Square(s);
shape[2] = new Rectangle(l, w);
shape[3] = new Trapezoid(t, b, h);
shape[4] = new Triangle(b, h);
double sum = 0; //计算所有图形面积的总和
for(int i = 0; i < 5; i++){
string name;
if(i == 0){ //输出各图形的面积
name = "Circle:";
}
else if(i == 1){
name = "Square:";
}
else if(i == 2){
name = "Rectangle:";
}
else if(i == 3){
name = "Trapezoid:";
}
else if(i == 4){
name = "Triangle:";
}
cout << name << shape[i]->getArea() << endl; //调用纯虚函数getArea
sum += shape[i]->getArea(); //累加面积
}
cout << "total of all areas=" << sum << endl; //输出所有图形面积的总和
return 0;
}
```
希望能够帮助您!