每个TwoDimensionShape包含getArea函数,计算二维图形的面积。每个ThreeDimensionShape包含getArea和getVolume函数,计算三维图形的表面积和体积。在主函数中,定义shape的指针数组,分别指向层次结构中的各个具体对象。输出每个对象。在循环中,处理所有图形,确定每个图形是TwoDimensionShape还是ThreeDimensionShape,如果图形是TwoDimensionShape,则显示它的面积。如果图形是ThreeDimensionShape,则显示三维图形的表面积和体积。
时间: 2024-02-25 22:53:12 浏览: 97
这是一个关于面向对象编程的问题。你可以定义一个基类Shape,包含纯虚函数getArea和getVolume,分别用于计算二维图形的面积和三维图形的表面积和体积。然后定义TwoDimensionShape和ThreeDimensionShape两个派生类,分别实现基类中的纯虚函数。
在主函数中,可以定义一个指针数组,指向Shape类的对象,分别指向各个具体对象。然后循环处理所有图形,通过dynamic_cast运算符判断每个图形是TwoDimensionShape还是ThreeDimensionShape。如果是TwoDimensionShape,则调用getArea函数计算面积并输出。如果是ThreeDimensionShape,则先调用getArea函数计算表面积,再调用getVolume函数计算体积,并输出这两个值。
下面是一个示例代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
public:
virtual double getArea() = 0;
virtual double getVolume() = 0;
};
class TwoDimensionShape : public Shape {
public:
virtual double getArea() = 0;
double getVolume() { return 0; }
};
class ThreeDimensionShape : public Shape {
public:
virtual double getArea() = 0;
virtual double getVolume() = 0;
};
class Circle : public TwoDimensionShape {
private:
double radius;
public:
Circle(double r) { radius = r; }
double getArea() { return M_PI * radius * radius; }
};
class Rectangle : public TwoDimensionShape {
private:
double width, height;
public:
Rectangle(double w, double h) { width = w; height = h; }
double getArea() { return width * height; }
};
class Sphere : public ThreeDimensionShape {
private:
double radius;
public:
Sphere(double r) { radius = r; }
double getArea() { return 4 * M_PI * radius * radius; }
double getVolume() { return 4.0/3.0 * M_PI * pow(radius, 3); }
};
class Cube : public ThreeDimensionShape {
private:
double length;
public:
Cube(double l) { length = l; }
double getArea() { return 6 * length * length; }
double getVolume() { return length * length * length; }
};
int main() {
Shape* shapes[4];
shapes[0] = new Circle(2);
shapes[1] = new Rectangle(3, 4);
shapes[2] = new Sphere(2);
shapes[3] = new Cube(3);
for (int i = 0; i < 4; i++) {
if (dynamic_cast<TwoDimensionShape*>(shapes[i])) {
cout << "Area of shape " << i+1 << ": " << shapes[i]->getArea() << endl;
}
else if (dynamic_cast<ThreeDimensionShape*>(shapes[i])) {
cout << "Surface area of shape " << i+1 << ": " << shapes[i]->getArea() << endl;
cout << "Volume of shape " << i+1 << ": " << shapes[i]->getVolume() << endl;
}
}
return 0;
}
```
阅读全文