用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 21:06:41 浏览: 215
c++ 形状类Shape(派生出圆类Circle和矩形类Rectangle)
```
#include<iostream>
#include<cmath>
#include<iomanip>
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.1415926 * 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 << setiosflags(ios::fixed) << setprecision(2) << s.area() << endl;
}
int main() {
double r, w, h, a, b, c;
cin >> r >> w >> h >> a >> b >> c;
Circle c1(r);
Rectangle r1(w, h);
Triangle t1(a, b, c);
printArea(c1);
printArea(r1);
printArea(t1);
return 0;
}
```
阅读全文