Shape类派生了Circle类和Rectangle类,请阅读主函数代码,完成Shape类、Circle类、Rectangle类的定义 【样例输入】 无 【样例输出】 Rectangle: Width=3.5,Height=7.2 Area=25.2 Perimeter=21.4 Circle: R=2.3 Area=16.619 Perimeter=14.4513 Shape Area=0 Perimeter=0 #include <iostream> #define PI 3.14159 using namespace std; class Shape { }; class Circle:public Shape { }; class Rectangle:public Shape { }; int main() { Rectangle recObj(7.2,3.5); recObj.print(); cout<<"Area="<<recObj.getArea()<<" Perimeter="<<recObj.getPerimeter()<<endl; Circle circleObj(2.3); circleObj.print(); cout<<"Area="<<circleObj.getArea()<<" Perimeter="<<circleObj.getPerimeter()<<endl; Shape shapeObj; shapeObj.print(); cout<<"Area="<<shapeObj.getArea()<<" Perimeter="<<shapeObj.getPerimeter()<<endl; return 0; }
时间: 2024-01-21 22:04:54 浏览: 131
c++程序编程
完成代码如下:
```cpp
#include <iostream>
#define PI 3.14159
using namespace std;
class Shape {
public:
virtual void print() {
cout << "Shape";
}
virtual double getArea() {
return 0;
}
virtual double getPerimeter() {
return 0;
}
};
class Circle : public Shape {
private:
double r;
public:
Circle(double r) {
this->r = r;
}
void print() {
cout << "Circle: R=" << r;
}
double getArea() {
return PI * r * r;
}
double getPerimeter() {
return 2 * PI * r;
}
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double width, double height) {
this->width = width;
this->height = height;
}
void print() {
cout << "Rectangle: Width=" << width << ",Height=" << height;
}
double getArea() {
return width * height;
}
double getPerimeter() {
return 2 * (width + height);
}
};
int main() {
Rectangle recObj(7.2, 3.5);
recObj.print();
cout << " Area=" << recObj.getArea() << " Perimeter=" << recObj.getPerimeter() << endl;
Circle circleObj(2.3);
circleObj.print();
cout << " Area=" << circleObj.getArea() << " Perimeter=" << circleObj.getPerimeter() << endl;
Shape shapeObj;
shapeObj.print();
cout << " Area=" << shapeObj.getArea() << " Perimeter=" << shapeObj.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
Shape Area=0 Perimeter=0
```
阅读全文