编写一个C++程序,定义抽象基类+Shape,由它派生出5+个派生类:Circle(圆形)Square(正方形)、Rectangle(矩形)、Trapezoid(梯形)、Triangle(三角形)。用
时间: 2024-06-13 16:07:26 浏览: 21
以下是一个C++程序,定义了抽象基类Shape,并由它派生出了5个派生类:Circle(圆形)、Square(正方形)、Rectangle(矩形)、Trapezoid(梯形)、Triangle(三角形)。程序中,每个类都有一个计算面积的函数,并且在每个类中都定义了相应的数据成员。
```c++
#include<iostream>
using namespace std;
class Shape{
public:
virtual double getArea() = 0; // 纯虚函数,计算面积
};
class Circle: public Shape{
public:
Circle(double r): radius(r){}
double getArea(){ return 3.14 * radius * radius; }
private:
double radius;
};
class Square: public Shape{
public:
Square(double l): length(l){}
double getArea(){ return length * length; }
private:
double length;
};
class Rectangle: public Shape{
public:
Rectangle(double l, double w): length(l), width(w){}
double getArea(){ return length * width; }
private:
double length;
double width;
};
class Trapezoid: public Shape{
public:
Trapezoid(double a, double b, double h): upper(a), lower(b), height(h){}
double getArea(){ return (upper + lower) * height / 2; }
private:
double upper;
double lower;
double height;
};
class Triangle: public Shape{
public:
Triangle(double a, double b, double c): length1(a), length2(b), length3(c){}
double getArea(){
double p = (length1 + length2 + length3) / 2;
return sqrt(p * (p - length1) * (p - length2) * (p - length3));
}
private:
double length1;
double length2;
double length3;
};
int main(){
Circle c(5);
Square s(4);
Rectangle r(3, 5);
Trapezoid t(2, 4, 3);
Triangle tr(3, 4, 5);
cout << "Circle area: " << c.getArea() << endl;
cout << "Square area: " << s.getArea() << endl;
cout << "Rectangle area: " << r.getArea() << endl;
cout << "Trapezoid area: " << t.getArea() << endl;
cout << "Triangle area: " << tr.getArea() << endl;
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)