summaryrefslogtreecommitdiff
path: root/chapter2/demo1.cxx
blob: 4c8bccaac9001cea6c59bcc3648f98cd72e71425 (plain) (blame)
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
// FILE: demo1.cxx
// This small demonstration shows how the throttle class is used.

#include <iostream>         // Provides cout and cin
#include <cstdlib>          // Provides EXIT_SUCCESS
using namespace std;        // Allows all Standard Library items to be used
class throttle
{
public:
    // MODIFICATION MEMBER FUNCTIONS
    void shut_off( );
    void shift(int amount);
    // CONSTANT MEMBER FUNCTIONS
    double flow( ) const;
    bool is_on( ) const;
private:
    int position;
};

int main( )
{
    throttle sample;
    int user_input;
    // Set the sample throttle to a position indicated by the user.
    cout << "I have a throttle with 6 positions." << endl;
    cout << "Where would you like to set the throttle? " << endl;
    cout << "Please type a number from 0 to 6: ";
    cin >> user_input;
    sample.shut_off( );
    sample.shift(user_input);
    // Shift the throttle down to zero, printing the flow along the way.
    while (sample.is_on( ))
    {
        cout << "The flow is now " << sample.flow( ) << endl;
        sample.shift(-1);
    }
    cout << "The flow is now off" << endl;
    return EXIT_SUCCESS;
}

void throttle::shut_off( )
// Precondition: None.
// Postcondition: The throttle has been turned off.
{
    position = 0;
}

double throttle::flow( ) const
// Precondition: shut_off has been called at least once to initialize the
// throttle.
// Postcondition: The value returned is the current flow as a proportion of
// the maximum flow.
{
    return position / 6.0;
}

void throttle::shift(int amount)
// Precondition: shut_off has been called at least once to initialize the
// throttle.
// Postcondition: The throttle's position has been moved by amount (but not
// below 0 or above 6).
{
    position += amount;

    // Adjust the throttle if it went too high or too low
    if (position < 0)
        position = 0;
    else if (position > 6)
        position = 6;
}

bool throttle::is_on( ) const
// Precondition: shut_off has been called at least once to initialize the
// throttle.
// Postcondition: If the throttle's flow is above 0 then the function
// returns true; otherwise it returns false.
{
    return (flow( ) > 0);
}