已知抽象基类Shape定义如下: class Shape{ public: virtual double area()const = 0; virtual void show ()const = 0; virtual ~Shape(){} };//---------------------------- (1)在类Shape定义基础上,定义Circle(圆), Triangle(三角形), Square(正方形), Rectangle(长方形)四个派生类,要求在派生类中对Shape中的area和show进行重新定义(area计算形状面积,show显示形状信息,比如Circle对象应该显示其半径和面积)。 (2)在以上类设计的基础上,编写普通函数及主函数解决以下问题:首先输入若干个形状, 第一个数字表达形状,0对应Circle, 1对应Triangle, 2对应Square,3对应Rectangle,比如输入0 3 , 得到的是一个半径为3的圆;接着把这些形状按面积从小到大排序;最后按排序后顺序输出每个形状的信息。 注:假设形状总数目不超过600个。 提示:定义一个指针数组,每个指针指向一个形状对象。
时间: 2023-10-06 21:11:40 浏览: 151
好的,下面是实现代码:
```
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class Shape {
public:
virtual double area() const = 0;
virtual void show() const = 0;
virtual ~Shape() {}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const {
return 3.14 * radius * radius;
}
void show() const {
cout << "Circle: radius = " << radius << ", area = " << area() << endl;
}
};
class Triangle : public Shape {
private:
double a, b, c;
public:
Triangle(double x, double y, double z) : a(x), b(y), c(z) {}
double area() const {
double p = (a + b + c) / 2;
return sqrt(p * (p - a) * (p - b) * (p - c));
}
void show() const {
cout << "Triangle: a = " << a << ", b = " << b << ", c = " << c << ", area = " << area() << endl;
}
};
class Square : public Shape {
private:
double side;
public:
Square(double s) : side(s) {}
double area() const {
return side * side;
}
void show() const {
cout << "Square: side = " << side << ", area = " << area() << endl;
}
};
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double area() const {
return length * width;
}
void show() const {
cout << "Rectangle: length = " << length << ", width = " << width << ", area = " << area() << endl;
}
};
bool cmp(const Shape* s1, const Shape* s2) {
return s1->area() < s2->area();
}
int main() {
Shape* shapes[600];
int cnt = 0;
while (true) {
int type;
cin >> type;
if (type == -1) {
break;
}
double a, b, c;
switch(type) {
case 0: // Circle
cin >> a;
shapes[cnt++] = new Circle(a);
break;
case 1: // Triangle
cin >> a >> b >> c;
shapes[cnt++] = new Triangle(a, b, c);
break;
case 2: // Square
cin >> a;
shapes[cnt++] = new Square(a);
break;
case 3: // Rectangle
cin >> a >> b;
shapes[cnt++] = new Rectangle(a, b);
break;
default:
break;
}
}
sort(shapes, shapes + cnt, cmp);
for (int i = 0; i < cnt; i++) {
shapes[i]->show();
delete shapes[i];
}
return 0;
}
```
在这个实现中,我们首先按照题目要求定义了Shape基类和四个派生类Circle、Triangle、Square和Rectangle,并分别重写了基类的虚函数area()和show(),用于计算各自的面积和输出各自的信息。然后在主函数中,我们使用一个指针数组来存储输入的形状对象,并对其按照面积从小到大排序,最后按顺序输出每个形状的信息。注意,在输出后需要手动释放每个形状对象的内存。
阅读全文