题目内容:定义抽象基类shape,由它派出4个派生类:Circle(圆形)、Rectangle(矩形)、Trapezoid(梯形)、Triangle(三角形);用虚函数实现几种图形面积的计算。要求Circle类、Rectangle类、Trapezoid类和Triangle类均要有带参数的构造函数。 输入格式: 第一行输入圆半径; 第二行输入矩形的长和宽; 第三行输入梯形的上边长、下边长、高; 第四行输入三角形的一个边长和高。 输出格式: 输出4种形状的面积(每行输出一个面积,小数点后面保留2位小数)。 输入样例: 1.0 1.0 2.0 1.0 2.0 3.0 1.0 2.0 输出样例: 3.14 2.00 4.50 1.00 c++
时间: 2023-07-16 17:13:54 浏览: 157
c++ 形状类Shape(派生出圆类Circle和矩形类Rectangle)
```
#include <iostream>
using namespace std;
class Shape {
public:
virtual double getArea() = 0; // 纯虚函数
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double getArea() {
return 3.14 * radius * radius;
}
};
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double getArea() {
return length * width;
}
};
class Trapezoid : public Shape {
private:
double upperLength, bottomLength, height;
public:
Trapezoid(double u, double b, double h) : upperLength(u), bottomLength(b), height(h) {}
double getArea() {
return (upperLength + bottomLength) * height / 2;
}
};
class Triangle : public Shape {
private:
double base, height;
public:
Triangle(double b, double h) : base(b), height(h) {}
double getArea() {
return base * height / 2;
}
};
int main() {
double r, l, w, u, b, h, base;
cin >> r >> l >> w >> u >> b >> h >> base;
Circle c(r);
Rectangle rect(l, w);
Trapezoid trape(u, b, h);
Triangle tri(base, h);
cout << fixed << setprecision(2) << c.getArea() << endl;
cout << fixed << setprecision(2) << rect.getArea() << endl;
cout << fixed << setprecision(2) << trape.getArea() << endl;
cout << fixed << setprecision(2) << tri.getArea() << endl;
return 0;
}
```
阅读全文