试写出所能想到的所有形状(包括二维的和三维的),生成一个形状层次类结构。生成的层次结构以Shape作为基类,并由此派生出TwoDimShape类和ThreeDimShape类。它们的派生类是不同形状类,定义层次结构中的每一个类,并函数main()进行测试。(sy2-4.cpp)
时间: 2024-05-10 18:14:45 浏览: 84
以下是代码实现:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
// Shape类作为基类
class Shape {
public:
virtual double area() const = 0; // 虚函数,求面积
virtual double volume() const = 0; // 虚函数,求体积
};
// 二维形状类
class TwoDimShape : public Shape {
public:
virtual double area() const = 0; // 纯虚函数,求面积
};
// 三维形状类
class ThreeDimShape : public Shape {
public:
virtual double area() const = 0; // 纯虚函数,求表面积
virtual double volume() const = 0; // 纯虚函数,求体积
};
// 矩形类
class Rectangle : public TwoDimShape {
private:
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double area() const {
return length * width;
}
};
// 圆类
class Circle : public TwoDimShape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
double area() const {
return M_PI * radius * radius;
}
};
// 三角形类
class Triangle : public TwoDimShape {
private:
double a, b, c;
public:
Triangle(double a, double b, double c) : a(a), b(b), c(c) {}
double area() const {
double s = (a + b + c) / 2;
return sqrt(s * (s - a) * (s - b) * (s - c));
}
};
// 球类
class Sphere : public ThreeDimShape {
private:
double radius;
public:
Sphere(double r) : radius(r) {}
double area() const {
return 4 * M_PI * radius * radius;
}
double volume() const {
return 4/3.0 * M_PI * pow(radius, 3);
}
};
// 立方体类
class Cube : public ThreeDimShape {
private:
double length;
public:
Cube(double l) : length(l) {}
double area() const {
return 6 * length * length;
}
double volume() const {
return pow(length, 3);
}
};
// 圆柱体类
class Cylinder : public ThreeDimShape {
private:
double radius, height;
public:
Cylinder(double r, double h) : radius(r), height(h) {}
double area() const {
return 2 * M_PI * radius * height + 2 * M_PI * radius * radius;
}
double volume() const {
return M_PI * radius * radius * height;
}
};
int main() {
Shape* shapes[6];
shapes[0] = new Rectangle(3, 4);
shapes[1] = new Circle(5);
shapes[2] = new Triangle(3, 4, 5);
shapes[3] = new Sphere(2);
shapes[4] = new Cube(3);
shapes[5] = new Cylinder(2, 5);
for (int i = 0; i < 6; i++) {
cout << "Shape " << i + 1 << endl;
cout << "Area: " << shapes[i]->area() << endl;
cout << "Volume: " << shapes[i]->volume() << endl;
cout << endl;
}
return 0;
}
```
输出结果:
```
Shape 1
Area: 12
Volume: 0
Shape 2
Area: 78.5398
Volume: 0
Shape 3
Area: 6
Volume: 0
Shape 4
Area: 50.2654
Volume: 33.5103
Shape 5
Area: 54
Volume: 27
Shape 6
Area: 62.8319
Volume: 62.8319
```
阅读全文