按照要求编写代码,并写出输出结果。 (1)类定义:定义一个 Shape 抽象类,在此基础上派生出 Rectangle 和 Circle,二者都有 GetArea()函数计算对象的面积,GetPerim()函数计算对象的周长。(10分) (2)main函数:在main函数中分别定义一个Rectangle和一个Circle对象,通过cin来指定Rectangle对象的长宽和Circle对象的半径。用cout分别输出这两个对象哪个面积更大,哪个周长更长。(10分)。
时间: 2024-03-20 12:42:40 浏览: 26
```c++
#include <iostream>
#include <cmath>
using namespace std;
// Shape类定义
class Shape {
public:
virtual double GetArea() = 0; // 计算面积的纯虚函数
virtual double GetPerim() = 0; // 计算周长的纯虚函数
};
// Rectangle类定义
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : width(w), height(h) {}
double GetArea() { return width * height; }
double GetPerim() { return 2 * (width + height); }
private:
double width;
double height;
};
// Circle类定义
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
double GetArea() { return M_PI * radius * radius; }
double GetPerim() { return 2 * M_PI * radius; }
private:
double radius;
};
int main() {
double w, h, r;
cout << "请输入长方形的宽和高:";
cin >> w >> h;
Rectangle rect(w, h);
cout << "请输入圆形的半径:";
cin >> r;
Circle circle(r);
if (rect.GetArea() > circle.GetArea()) {
cout << "长方形的面积更大" << endl;
} else {
cout << "圆形的面积更大" << endl;
}
if (rect.GetPerim() > circle.GetPerim()) {
cout << "长方形的周长更长" << endl;
} else {
cout << "圆形的周长更长" << endl;
}
return 0;
}
```
输出结果:根据输入的长方形的宽和高以及圆形的半径,程序会先输出哪个对象的面积更大,然后输出哪个对象的周长更长。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)