用c++写出n Define a class Circle and derive the class Cylinder from the class Circle. n The specific requirements are as follows: l In the main function, input the radius of the circle and output the area of the corresponding circle. Then, input the height of the cylinder, output the surface area and volume of the corresponding cylinder.
时间: 2024-02-20 20:01:50 浏览: 90
Sure, here's an example implementation of the classes Circle and Cylinder in C++:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
class Circle {
public:
Circle(double r) : radius(r) {}
double area() {
return M_PI * pow(radius, 2);
}
protected:
double radius;
};
class Cylinder : public Circle {
public:
Cylinder(double r, double h) : Circle(r), height(h) {}
double surface_area() {
return 2 * M_PI * radius * height + 2 * Circle::area();
}
double volume() {
return Circle::area() * height;
}
private:
double height;
};
int main() {
double radius, height;
cout << "Enter the radius of the circle: ";
cin >> radius;
Circle circle(radius);
cout << "The area of the circle is " << circle.area() << endl;
cout << "Enter the height of the cylinder: ";
cin >> height;
Cylinder cylinder(radius, height);
cout << "The surface area of the cylinder is " << cylinder.surface_area() << endl;
cout << "The volume of the cylinder is " << cylinder.volume() << endl;
return 0;
}
```
In the `Circle` class, we define a constructor that takes a `double` argument for the radius of the circle and a method `area()` that calculates and returns the area of the circle.
In the `Cylinder` class, we define a constructor that takes two `double` arguments for the radius and height of the cylinder. We also define two methods `surface_area()` and `volume()` that calculate and return the surface area and volume of the cylinder, respectively. These methods make use of the inherited `area()` method of the `Circle` class to calculate the area of the circular base of the cylinder.
In `main()`, we prompt the user to enter the radius of the circle and the height of the cylinder, create objects of the `Circle` and `Cylinder` classes with the given values, and output the computed area, surface area, and volume using their respective methods.
阅读全文