-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsphere_class_example.cpp
More file actions
92 lines (80 loc) · 1.7 KB
/
sphere_class_example.cpp
File metadata and controls
92 lines (80 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <cassert>
#include <cmath>
#include <stdexcept>
class Sphere {
public:
/**
* @brief Sphere constructor
*
* @param[in] radius: sets the radius of the sphere
*
* @throws invalid_argument exception if values passed in <= 0
*/
Sphere(int radius);
// Accessors
int Radius() const { return radius_; }
int Volume() const { return volume_; }
// Mutators
/**
* @brief radius_setter
*
* @param[in] radius: sets the radius of the sphere
*
* @throws invalid_argument exception if values passed in <= 0
*/
void Radius(int radius);
private:
// Private members
static float constexpr kPi{3.14159};
int radius_;
float volume_;
/**
* @brief Checks that the set radius is > 0, if so sets the volume
*
* @throws invalid_argument exception if values passed in <= 0
*/
void SetVolume();
};
Sphere::Sphere(int radius) : radius_(radius)
{
SetVolume();
}
void Sphere::SetVolume()
{
if (radius_ <= 0) {
throw std::invalid_argument("radius must be positive");
}
volume_ = kPi * 4./3. * pow(radius_, 3);
}
void Sphere::Radius(int radius)
{
radius_ = radius;
SetVolume();
}
// Show static members example with this class
class Sphere2 {
public:
static float Volume(int radius)
{
return pi_ * 4/3 * pow(radius,3);
}
private:
static float constexpr pi_{3.14159};
};
// Test
int main(void) {
Sphere sphere(5);
assert(sphere.Radius() == 5);
assert(abs(sphere.Volume() - 523.6) < 1);
sphere.Radius(3);
assert(sphere.Radius() == 3);
assert(abs(sphere.Volume() - 113.1) < 1);
bool caught{false};
try {
sphere.Radius(-1);
} catch (...) {
caught = true;
}
assert(caught);
assert(abs(Sphere2::Volume(5) - 523.6) < 1);
}