声明一个Shape抽象类,在此基础上派生出矩形Rectangle和圆Circle类,二者都有GetArea( )函数计算对象的面积,GetPerim( )函数计算对象的周长。完成类的设计,其中PI取3.14159。 主程序如下(不能修改): int main() {
时间: 2024-02-05 09:11:14 浏览: 65
以下是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 {
public:
Rectangle(double l, double w) : length(l), width(w) {}
double GetArea() override {
return length * width;
}
double GetPerim() override {
return 2 * (length + width);
}
private:
double length;
double width;
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
double GetArea() override {
return PI * radius * radius;
}
double GetPerim() override {
return 2 * PI * radius;
}
private:
double radius;
};
```
在主程序中,我们可以使用指向基类对象的指针,来调用不同派生类对象的同名函数,从而实现多态。
```c++
int main() {
Shape* shape1 = new Rectangle(3, 4);
cout << "Rectangle area: " << shape1->GetArea() << endl;
cout << "Rectangle perimeter: " << shape1->GetPerim() << endl;
delete shape1;
Shape* shape2 = new Circle(5);
cout << "Circle area: " << shape2->GetArea() << endl;
cout << "Circle perimeter: " << shape2->GetPerim() << endl;
delete shape2;
return 0;
}
```
阅读全文