1. Construct a class named sphere that has a double-precision data member named radius. The class should have the following class functions: i. A constructor with the default values of 1 for radius data member. ii. An accessor function named showData() that displays a sphere’s radius. iii. A mutator function named setData() to set a sphere’s radius. iv. A class function named surfaceArea() that calculates and displays a sphere’s surface area. v. A class function named volume() that calculates and displays a sphere’s vol
时间: 2024-03-10 11:45:56 浏览: 21
ume.
Here's an example implementation of the sphere class in C++:
```c++
#include <iostream>
#include <cmath>
class sphere {
private:
double radius;
public:
sphere() {
radius = 1.0;
}
void showData() {
std::cout << "Sphere radius: " << radius << std::endl;
}
void setData(double r) {
radius = r;
}
double surfaceArea() {
return 4 * M_PI * radius * radius;
}
double volume() {
return 4.0 / 3.0 * M_PI * pow(radius, 3);
}
};
int main() {
sphere mySphere;
mySphere.showData();
mySphere.setData(2.0);
std::cout << "Sphere surface area: " << mySphere.surfaceArea() << std::endl;
std::cout << "Sphere volume: " << mySphere.volume() << std::endl;
return 0;
}
```
In this implementation, the sphere class has a private data member `radius` and five public member functions:
- A default constructor that initializes the `radius` to 1.0.
- An accessor function `showData()` that displays the current value of `radius`.
- A mutator function `setData()` that sets the value of `radius`.
- A class function `surfaceArea()` that calculates and returns the surface area of the sphere.
- A class function `volume()` that calculates and returns the volume of the sphere.
In the `main()` function, we create a `sphere` object `mySphere`, display its initial radius using the `showData()` function, set its radius to 2.0 using the `setData()` function, and then display its surface area and volume using the `surfaceArea()` and `volume()` functions, respectively.