具体要求如下: ①定义平面二维点类CPoint,有数据成员x坐标,y坐标,函数成员(构造函数、纯虚函数求面积GetArea,纯虚函数求体积函数GetVolume、输出点信息函数print。 ②由CPoint类派生出圆类Cirle类(新增数据成员半径radius),函数成员(构造函数、求面积GetArea,虚函数求体积函数GetVolume、输出圆信息函数print。 ③再由Cirle类派生出圆柱体Ccylinder类(新增数据成员高度height),函数成员(构造函数、复制构造函数、求表面积GetArea,求体积函数GetVolume、输出圆柱体信息函数print。 ④在主函数测试这个这三个类。
时间: 2024-02-12 12:08:17 浏览: 40
好的,您的问题是如何定义一个平面二维点类CPoint并且从它派生出一个圆类Cirle和圆柱体类Ccylinder,实现相应的函数成员和数据成员,以及在主函数中进行测试。
首先,我们来定义CPoint类:
```cpp
class CPoint {
public:
CPoint(double x = 0, double y = 0) : m_x(x), m_y(y) {}
virtual ~CPoint() {}
virtual double GetArea() const = 0;
virtual double GetVolume() const = 0;
virtual void print() const {
std::cout << "Point(" << m_x << ", " << m_y << ")" << std::endl;
}
protected:
double m_x;
double m_y;
};
```
在CPoint类中,我们定义了两个数据成员m_x和m_y,表示二维坐标系中点的x坐标和y坐标。同时,我们还定义了构造函数和纯虚函数GetArea()和GetVolume(),print()函数用于输出点的信息。
接下来,我们从CPoint类派生出一个圆类Cirle:
```cpp
class Cirle : public CPoint {
public:
Cirle(double x = 0, double y = 0, double r = 0) : CPoint(x, y), m_radius(r) {}
virtual ~Cirle() {}
virtual double GetArea() const {
return M_PI * m_radius * m_radius;
}
virtual double GetVolume() const {
return 0;
}
virtual void print() const {
std::cout << "Cirle(" << m_x << ", " << m_y << ", " << m_radius << ")" << std::endl;
}
protected:
double m_radius;
};
```
在Cirle类中,我们新增了一个数据成员m_radius,表示圆的半径。同时,我们重写了GetArea()函数,用于计算圆的面积,GetVolume()函数返回0,因为圆没有体积。print()函数用于输出圆的信息。
最后,我们从Cirle类派生出一个圆柱体类Ccylinder:
```cpp
class Ccylinder : public Cirle {
public:
Ccylinder(double x = 0, double y = 0, double r = 0, double h = 0) : Cirle(x, y, r), m_height(h) {}
Ccylinder(const Ccylinder& other) : Cirle(other), m_height(other.m_height) {}
virtual ~Ccylinder() {}
virtual double GetArea() const {
return 2 * M_PI * m_radius * m_height + 2 * M_PI * m_radius * m_radius;
}
virtual double GetVolume() const {
return M_PI * m_radius * m_radius * m_height;
}
virtual void print() const {
std::cout << "Ccylinder(" << m_x << ", " << m_y << ", " << m_radius << ", " << m_height << ")" << std::endl;
}
protected:
double m_height;
};
```
在Ccylinder类中,我们新增了一个数据成员m_height,表示圆柱体的高度。我们重写了GetArea()和GetVolume()函数,用于计算圆柱体的表面积和体积。print()函数用于输出圆柱体的信息。
最后,在主函数中进行测试:
```cpp
int main() {
CPoint* p1 = new CPoint(1, 2);
p1->print();
std::cout << "Area = " << p1->GetArea() << ", Volume = " << p1->GetVolume() << std::endl;
Cirle* p2 = new Cirle(3, 4, 5);
p2->print();
std::cout << "Area = " << p2->GetArea() << ", Volume = " << p2->GetVolume() << std::endl;
Ccylinder* p3 = new Ccylinder(6, 7, 8, 9);
p3->print();
std::cout << "Area = " << p3->GetArea() << ", Volume = " << p3->GetVolume() << std::endl;
delete p1;
delete p2;
delete p3;
return 0;
}
```
在主函数中,我们分别创建了一个CPoint对象、一个Cirle对象和一个Ccylinder对象,然后调用它们的print()函数、GetArea()函数和GetVolume()函数进行输出和计算。最后记得释放动态分配的内存。