请用c++编写一个抽象类Shape,在此基础上派生出类Rectangle和Circle,二者都有计算对象面积的函数GetArea()、计算对象周长的函数GetPerim()。在主函数中定义抽象类的对象指针数组实现对不同派生类对象及其成员函数的测试
时间: 2024-02-20 13:59:28 浏览: 34
好的,下面是代码实现:
```c++
#include <iostream>
using namespace std;
// 抽象类Shape
class Shape {
public:
virtual double GetArea() = 0; // 纯虚函数,用于计算面积
virtual double GetPerim() = 0; // 纯虚函数,用于计算周长
};
// 派生类Rectangle
class Rectangle : public Shape {
public:
Rectangle(double _length, double _width) : length(_length), width(_width) {}
double GetArea() {
return length * width;
}
double GetPerim() {
return 2 * (length + width);
}
private:
double length;
double width;
};
// 派生类Circle
class Circle : public Shape {
public:
Circle(double _radius) : radius(_radius) {}
double GetArea() {
return 3.14159 * radius * radius;
}
double GetPerim() {
return 2 * 3.14159 * radius;
}
private:
double radius;
};
int main() {
Shape* shapes[2]; // 抽象类的对象指针数组
shapes[0] = new Rectangle(3, 4); // 指向Rectangle对象
shapes[1] = new Circle(5); // 指向Circle对象
for (int i = 0; i < 2; i++) {
cout << "对象" << i+1 << "的面积为:" << shapes[i]->GetArea() << endl;
cout << "对象" << i+1 << "的周长为:" << shapes[i]->GetPerim() << endl;
}
return 0;
}
```
运行结果为:
```
对象1的面积为:12
对象1的周长为:14
对象2的面积为:78.5398
对象2的周长为:31.4159
```
可以看到,我们成功地实现了抽象类Shape,以及其派生类Rectangle和Circle,使用对象指针数组对不同派生类的对象进行了测试,输出了面积和周长。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)