已有抽象类shape定义如下,该类提供三个纯虚函数;显示数据成员、返回面积和返回体积。 Class Shape { virtual void showData()=0; virtual double reArea()=0; virtual double reVolume()=0; }; 以Shape为顶层基类,派生TwoDimShape(二维图形)和ThreeShape(三维图形)两个类,它们增加了有关的数据成员(自己设定,各自不少于2个),但没有成员函数的实现。 第三层派生具体的图形类。TwoDimShape类派生Circle(圆)、Elipse(椭圆)、Rectangle(矩形)和Triangle(三角形)等类。ThreeShape类派生Ball(球体)、Cylinder(圆柱体)、RectangularParallelepiped(长方体)等类。 在主函数测试中使用多态方式调用不同对象的求面积和体积等函数。
时间: 2024-01-17 21:06:10 浏览: 24
好的,这是一个关于面向对象编程的问题。基于上述类的定义,您需要完成以下任务:
1. 定义TwoDimShape和ThreeShape两个类,分别继承Shape,并添加自己的数据成员(不少于2个)。
2. 定义派生自TwoDimShape的Circle、Elipse、Rectangle和Triangle,以及派生自ThreeShape的Ball、Cylinder、RectangularParallelepiped等类,分别实现其父类中的纯虚函数。
3. 在主函数中,使用多态方式创建不同的对象,并调用其成员函数求面积和体积等函数。
下面是一个基本的实现示例:
```cpp
#include <iostream>
using namespace std;
class Shape {
public:
virtual void showData() = 0;
virtual double reArea() = 0;
virtual double reVolume() = 0;
};
class TwoDimShape : public Shape {
protected:
double width;
double height;
public:
TwoDimShape(double w, double h) : width(w), height(h) {}
};
class Circle : public TwoDimShape {
public:
Circle(double r) : TwoDimShape(r, r) {}
void showData() { cout << "Circle radius: " << width << endl; }
double reArea() { return 3.1415926 * width * width; }
double reVolume() { return 0; }
};
class ThreeShape : public Shape {
protected:
double width;
double height;
double depth;
public:
ThreeShape(double w, double h, double d) : width(w), height(h), depth(d) {}
};
class Cylinder : public ThreeShape {
public:
Cylinder(double r, double h) : ThreeShape(r, h, 0) {}
void showData() { cout << "Cylinder radius: " << width << ", height: " << height << endl; }
double reArea() { return 2 * 3.1415926 * width * height + 2 * 3.1415926 * width * width; }
double reVolume() { return 3.1415926 * width * width * height; }
};
int main() {
Shape* p;
Circle c(5);
Cylinder cy(3, 5);
p = &c;
p->showData();
cout << "Area: " << p->reArea() << endl;
cout << "Volume: " << p->reVolume() << endl;
p = &cy;
p->showData();
cout << "Area: " << p->reArea() << endl;
cout << "Volume: " << p->reVolume() << endl;
return 0;
}
```
上述示例中,我们定义了Shape作为顶层基类,TwoDimShape和ThreeShape两个类分别继承Shape。Circle、Elipse、Rectangle和Triangle等类派生自TwoDimShape,Ball、Cylinder、RectangularParallelepiped等类派生自ThreeShape。
在主函数中,我们使用指针p多态地创建了Circle和Cylinder两个对象,并调用其成员函数求面积和体积。