用C++编写一个程序满足已知抽象类Shape及Shape类的3个公有派生类圆类Circle、矩形类Rectangle、三角形类Triangle声明如下: class Shape { public: virtual double area() const = 0; }; class Circle:public Shape { public: Circle(double r); virtual double area() const; protected: double m_radius; }; class Rectangle:public Shape { public: Rectangle(double w, double h); virtual double area() const; protected: double m_width, m_height; }; class Triangle:public Shape { public: Triangle(double a, double b, double c); virtual double area() const; protected: double m_a, m_b, m_c; }; 试完成成员函数的定义,在主函数中输入圆的半径、矩形的宽和高、三角形的三条边,定义对象,利用函数void printArea(const Shape &s)输出圆、矩形及三角形的面积。 输入 三行,第1行圆的半径,第2行矩形的宽和高,第3行三角形的三条边。 输出 圆、矩形及三角形的面积(取2位小数)。
时间: 2023-06-18 19:08:41 浏览: 104
以下是代码实现:
```c++
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
class Shape {
public:
virtual double area() const = 0;
};
class Circle:public Shape {
public:
Circle(double r) {
m_radius = r;
}
virtual double area() const {
return 3.14 * m_radius * m_radius;
}
protected:
double m_radius;
};
class Rectangle:public Shape {
public:
Rectangle(double w, double h) {
m_width = w;
m_height = h;
}
virtual double area() const {
return m_width * m_height;
}
protected:
double m_width, m_height;
};
class Triangle:public Shape {
public:
Triangle(double a, double b, double c) {
m_a = a;
m_b = b;
m_c = c;
}
virtual double area() const {
double p = (m_a + m_b + m_c) / 2.0;
return sqrt(p * (p - m_a) * (p - m_b) * (p - m_c));
}
protected:
double m_a, m_b, m_c;
};
void printArea(const Shape &s) {
cout << fixed << setprecision(2) << "面积为:" << s.area() << endl;
}
int main() {
double r, w, h, a, b, c;
cin >> r >> w >> h >> a >> b >> c;
Circle circle(r);
Rectangle rectangle(w, h);
Triangle triangle(a, b, c);
cout << "圆的";
printArea(circle);
cout << "矩形的";
printArea(rectangle);
cout << "三角形的";
printArea(triangle);
return 0;
}
```
输入示例:
```
2
3 4
3 4 5
```
输出示例:
```
圆的面积为:12.56
矩形的面积为:12.00
三角形的面积为:6.00
```
阅读全文