定义一个Shape基类,并派生出圆球体(Sphere)和立方体类(Cube),输入半径,分别求圆球体与立方体对象的表面积和体积。
时间: 2024-02-03 12:04:41 浏览: 21
好的,我可以帮你解答这个问题。
首先,我们需要定义一个Shape基类,其中包含计算表面积和体积的虚函数,这些函数将由派生类实现。具体代码如下:
```c++
class Shape {
public:
virtual float surface_area() const = 0;
virtual float volume() const = 0;
};
```
接下来,我们需要派生出圆球体类Sphere和立方体类Cube,并实现它们的表面积和体积计算函数。具体代码如下:
```c++
#include <cmath>
class Sphere : public Shape {
public:
Sphere(float r) : radius(r) {}
float surface_area() const override {
return 4 * M_PI * pow(radius, 2);
}
float volume() const override {
return 4.0 / 3 * M_PI * pow(radius, 3);
}
private:
float radius;
};
class Cube : public Shape {
public:
Cube(float l) : length(l) {}
float surface_area() const override {
return 6 * pow(length, 2);
}
float volume() const override {
return pow(length, 3);
}
private:
float length;
};
```
最后,我们可以在主函数中创建Sphere和Cube对象,并调用它们的表面积和体积计算函数来得到结果。具体代码如下:
```c++
#include <iostream>
int main() {
float r, l;
std::cout << "Enter the radius of the sphere: ";
std::cin >> r;
Sphere s(r);
std::cout << "Surface area of the sphere: " << s.surface_area() << std::endl;
std::cout << "Volume of the sphere: " << s.volume() << std::endl;
std::cout << "Enter the length of the cube: ";
std::cin >> l;
Cube c(l);
std::cout << "Surface area of the cube: " << c.surface_area() << std::endl;
std::cout << "Volume of the cube: " << c.volume() << std::endl;
return 0;
}
```
这样,在输入半径和边长后,程序会输出圆球体和立方体的表面积和体积。