编写程序计算长方形的面积和长方体的体积。要求如下: (1)定义一个基类Point,至少有2个数据成员用来表示点的位置信息:X,Y; (2)定义基类的派生类:长方形和长方体,含有求面积和体积的成员函数以及信息输出函数; (3)定义主函数,求长方形面积和长方体的体积。用c++作答
时间: 2024-02-21 16:02:07 浏览: 26
好的,下面是符合要求的C++代码:
```c++
#include <iostream>
using namespace std;
class Point {
public:
Point(int x, int y) : m_x(x), m_y(y) {}
Point() : m_x(0), m_y(0) {}
void setPoint(int x, int y) { m_x = x; m_y = y; }
int getX() const { return m_x; }
int getY() const { return m_y; }
private:
int m_x, m_y;
};
class Rectangle : public Point {
public:
Rectangle(int x, int y, int w, int h) : Point(x, y), m_width(w), m_height(h) {}
Rectangle() : Point(), m_width(0), m_height(0) {}
int getWidth() const { return m_width; }
int getHeight() const { return m_height; }
void setWidth(int w) { m_width = w; }
void setHeight(int h) { m_height = h; }
void printInfo() const {
cout << "Rectangle: position=(" << getX() << "," << getY() << ") width=" << m_width << " height=" << m_height << endl;
}
int getArea() const { return m_width * m_height; }
private:
int m_width, m_height;
};
class Cuboid : public Point {
public:
Cuboid(int x, int y, int z, int w, int h, int d) : Point(x, y), m_width(w), m_height(h), m_depth(d) {
m_position.setPoint(x, y);
m_position.setPoint(z);
}
Cuboid() : Point(), m_width(0), m_height(0), m_depth(0) {}
int getWidth() const { return m_width; }
int getHeight() const { return m_height; }
int getDepth() const { return m_depth; }
void setWidth(int w) { m_width = w; }
void setHeight(int h) { m_height = h; }
void setDepth(int d) { m_depth = d; }
void printInfo() const {
cout << "Cuboid: position=(" << getX() << "," << getY() << "," << m_position.getZ() << ") width=" << m_width << " height=" << m_height << " depth=" << m_depth << endl;
}
int getVolume() const { return m_width * m_height * m_depth; }
private:
int m_width, m_height, m_depth;
Point m_position;
};
int main() {
Rectangle rect(1, 2, 3, 4);
rect.printInfo();
cout << "Rectangle area: " << rect.getArea() << endl;
Cuboid cuboid(1, 2, 3, 4, 5, 6);
cuboid.printInfo();
cout << "Cuboid volume: " << cuboid.getVolume() << endl;
return 0;
}
```
在这个程序中,我们定义了一个基类Point,表示一个点的位置信息。然后我们定义了两个派生类Rectangle和Cuboid,分别表示长方形和长方体。这两个类都有求面积或体积的成员函数,以及输出信息的函数printInfo。在主函数中,我们创建了一个Rectangle对象和一个Cuboid对象,并分别输出它们的信息和面积/体积。