声明一个Shape抽象类,在此基础上派生出矩形Rectangle和圆Circle类,二者都有GetArea( )函数计算对象的面积,GetPerim( )函数计算对象的周长。完成类的设计,其中PI取3.14159。 主程序如下(不能修改): int main() { double radius; //圆半径 double a,b; //矩形长和宽 cin >> radius >> a >> b; Circle c(radius); Rectangle rect(a, b); Shape* pShapeArray[] = {&c, &rect}; for (int i = 0; i < 2; i++) { cout << "perimeter:" << pShapeArray[i]->GetPerim( ) << endl; cout << "area:" << pShapeArray[i]->GetArea() << endl; } return 0; }
时间: 2024-01-07 15:03:27 浏览: 99
编写一个抽象类Shape
4星 · 用户满意度95%
以下是Shape、Rectangle和Circle类的设计:
```c++
#include <iostream>
using namespace std;
const double PI = 3.14159;
class Shape {
public:
virtual double GetArea() = 0; // 纯虚函数,计算面积
virtual double GetPerim() = 0; // 纯虚函数,计算周长
};
class Rectangle : public Shape {
private:
double length;
double width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
double GetArea() {
return length * width;
}
double GetPerim() {
return 2 * (length + width);
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) {
radius = r;
}
double GetArea() {
return PI * radius * radius;
}
double GetPerim() {
return 2 * PI * radius;
}
};
```
在主程序中,定义一个Shape类型的指针数组,将Circle和Rectangle对象的地址存储在其中。通过循环遍历该数组,分别调用每个对象的GetArea和GetPerim函数输出结果。
```c++
int main() {
double radius;
double a, b;
cin >> radius >> a >> b;
Circle c(radius);
Rectangle rect(a, b);
Shape* pShapeArray[] = { &c, &rect };
for (int i = 0; i < 2; i++) {
cout << "perimeter:" << pShapeArray[i]->GetPerim() << endl;
cout << "area:" << pShapeArray[i]->GetArea() << endl;
}
return 0;
}
```
阅读全文