使用虚函数编写程序求球体和圆柱体的体积和表面积。具体要求如下: (1)由于球体和圆柱体都可以看作由圆继承而来,所以可以定义圆类Circle为基类;在Circle类中定义求圆面积和体积的函数。 (2)由Circle类派生出
时间: 2024-03-12 13:48:04 浏览: 87
Sphere类和Cylinder类,分别表示球体和圆柱体。在这两个类中分别定义虚函数求表面积和体积。
下面是程序实现:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Circle {
public:
Circle(double r) : radius(r) {}
virtual double getArea() const { // 圆面积
return M_PI * radius * radius;
}
virtual double getVolume() const = 0; // 纯虚函数,求体积
protected:
double radius;
};
class Sphere : public Circle {
public:
Sphere(double r) : Circle(r) {}
virtual double getArea() const { // 球表面积
return 4 * M_PI * radius * radius;
}
virtual double getVolume() const { // 球体积
return 4.0 / 3.0 * M_PI * pow(radius, 3);
}
};
class Cylinder : public Circle {
public:
Cylinder(double r, double h) : Circle(r), height(h) {}
virtual double getArea() const { // 圆柱表面积
return 2 * M_PI * radius * height + 2 * Circle::getArea();
}
virtual double getVolume() const { // 圆柱体积
return Circle::getArea() * height;
}
private:
double height;
};
int main() {
Circle* p;
double r, h;
cout << "请输入球半径和圆柱底面半径、高度:";
cin >> r >> h;
p = new Sphere(r);
cout << "球的表面积为:" << p->getArea() << ",体积为:" << p->getVolume() << endl;
delete p;
p = new Cylinder(r, h);
cout << "圆柱的表面积为:" << p->getArea() << ",体积为:" << p->getVolume() << endl;
delete p;
return 0;
}
```
程序中定义了圆类Circle作为基类,其中定义了求圆面积的函数getArea()和纯虚函数求体积getVolume()。派生类Sphere和Cylinder分别表示球体和圆柱体,其中重写了getArea()函数求表面积,实现了getVolume()函数求体积。在主函数中,通过指针调用不同的对象的函数,实现了多态。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)