int main() { Rectangle recA(7.2,3.5), recB(7.2,3.5); Circle circleA(2.3), circleB(1.5); Shape *pShape[4]={&recB, &circleA, &circleB, &recA}; for( int i=0; i<4; i++) { pShape[i]->print(); cout<<"Area="<< pShape[i]->getArea()<<" Perimeter="<< pShape[i]->getPerimeter()<<endl; } return 0; } 它的主函数为上面代码,请补充之前的代码
时间: 2024-01-15 22:03:33 浏览: 140
好的,这里需要补充的代码如下:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
// 定义抽象类 Shape
class Shape {
public:
virtual double getArea() = 0;
virtual double getPerimeter() = 0;
virtual void print() = 0;
};
// 定义 Circle 类
class Circle : public Shape {
private:
double r;
public:
Circle(double r) : r(r) {}
double getArea() { return M_PI * r * r; }
double getPerimeter() { return 2 * M_PI * r; }
void print() { cout << "Circle: R=" << r << " "; }
};
// 定义 Rectangle 类
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double width, double height) : width(width), height(height) {}
double getArea() { return width * height; }
double getPerimeter() { return 2 * (width + height); }
void print() { cout << "Rectangle: Width=" << width << ",Height=" << height << " "; }
};
```
这里我们定义了一个抽象类 Shape,里面包含了纯虚函数 getArea() 和 getPerimeter(),以及虚函数 print()。然后我们在 Circle 和 Rectangle 类中继承了 Shape 类,并实现了相应的虚函数。
接下来是主函数代码,它可以输出每个图形的类型、参数以及面积和周长:
```cpp
int main() {
Rectangle recA(7.2, 3.5), recB(7.2, 3.5);
Circle circleA(2.3), circleB(1.5);
Shape *pShape[4] = {&recB, &circleA, &circleB, &recA};
for (int i = 0; i < 4; i++) {
pShape[i]->print();
cout << "Area=" << pShape[i]->getArea() << " Perimeter=" << pShape[i]->getPerimeter() << endl;
}
return 0;
}
```
输出结果为:
```
Rectangle: Width=7.2,Height=3.5 Area=25.2 Perimeter=21.4
Circle: R=2.3 Area=16.619 Perimeter=14.4513
Circle: R=1.5 Area=7.06858 Perimeter=9.42477
Rectangle: Width=7.2,Height=3.5 Area=25.2 Perimeter=21.4
```
阅读全文