93 lines
1.9 KiB
C++
93 lines
1.9 KiB
C++
// 继第6题, 基于多态方式,定义一个全局函数排序函数,接收Shape类的数组,并按形状的周长进行从大到少排序。
|
||
// 【提示】全局函数排序函数 void sort(Shape *arr, int size)
|
||
#include <iostream>
|
||
#include <cstring>
|
||
#include <cstdlib>
|
||
|
||
using namespace std;
|
||
|
||
class Shape
|
||
{
|
||
public:
|
||
// 用于计算形状的周长
|
||
virtual double perimeter() = 0;
|
||
};
|
||
|
||
class Triangle : public Shape
|
||
{
|
||
private:
|
||
double a, b, c;
|
||
|
||
public:
|
||
Triangle(double a, double b, double c) : a(a), b(b), c(c) {}
|
||
|
||
public:
|
||
double perimeter()
|
||
{
|
||
return a + b + c;
|
||
}
|
||
};
|
||
|
||
class Square : public Shape
|
||
{
|
||
private:
|
||
double a;
|
||
|
||
public:
|
||
Square(double a) : a(a) {}
|
||
|
||
public:
|
||
double perimeter()
|
||
{
|
||
return 4 * a;
|
||
}
|
||
};
|
||
|
||
void sort(Shape *arr[], int size) // 这里为什么传指针数组?因为 Shape 是抽象类,不能实例化对象,只能通过指针来操作
|
||
{
|
||
for (int i = 0; i < size - 1; i++)
|
||
{
|
||
for (int j = 0; j < size - i - 1; j++)
|
||
{
|
||
// 比较形状的周长
|
||
if (arr[j]->perimeter() < arr[j + 1]->perimeter())
|
||
{
|
||
// 交换位置
|
||
swap(arr[j], arr[j + 1]);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
int main()
|
||
{
|
||
Shape *p = new Triangle(3, 4, 5);
|
||
Shape *q = new Square(5);
|
||
Shape *r = new Triangle(6, 8, 10);
|
||
Shape *s = new Square(10);
|
||
Shape *t = new Triangle(5, 12, 13);
|
||
Shape *u = new Square(13);
|
||
// Shape *arr[6];
|
||
// arr[0] = p;
|
||
// arr[1] = q;
|
||
Shape *arr[] = {p, q, r, s, t, u}; // arr作为一个指针数组,存了6个指向 Shape 类对象的指针
|
||
int len = sizeof(arr) / sizeof(arr[0]);
|
||
|
||
cout << "排序前:" << endl;
|
||
|
||
for (int i = 0; i < len; i++)
|
||
{
|
||
cout << arr[i]->perimeter() << endl;
|
||
}
|
||
|
||
sort(arr, len);
|
||
|
||
cout << "排序后:" << endl;
|
||
for (int i = 0; i < len; i++)
|
||
{
|
||
cout << arr[i]->perimeter() << endl;
|
||
}
|
||
|
||
return 0;
|
||
}
|