class Time
1: // Filenme: TCLASS.CPP
2: // Purpose: Illustrates a simple class for representing time.
4: #include <iostream>
5: using namespace std;
8: class Time
9: {
10: public:
11: //******************************************************************
12: void Set(/* in */ int hoursNew,
13: /* in */ int minutesNew,
14: /* in */ int secondsNew)
15: // Pre: 0 <= hoursNew <= 23
16: // 0 <= minutesNew <= 59
17: // 0 <= secondsNew <= 59
18: // Post: Time is set according to the incoming parameters.
19: // Note that this function MUST have been called prior to
20: // any call to *any* of the other member functions.
21: {
22: hours = hoursNew;
23: minutes = minutesNew;
24: seconds = secondsNew;
25: }
28: //******************************************************************
29: void Increment()
30: // Pre: The Set function has been called at least once.
31: // Post: Time has been advanced by one second, with
32: // 23:59:59 wrapping around to 0:0:0.
33: {
34: seconds++;
35: if (seconds > 59)
36: {
37: seconds = 0;
38: minutes++;
39: if (minutes > 59)
40: {
41: minutes = 0;
42: hours++;
43: if (hours > 23)
44: hours = 0;
45: }
46: }
47: }
50: //******************************************************************
51: void Display() const
52: // Pre: The Set function has been called at least once.
53: // Post: Time has been output in the form HH:MM:SS.
54: {
55: if (hours < 10)
56: cout << '0';
57: cout << hours << ':';
58: if (minutes < 10)
59: cout << '0';
60: cout << minutes << ':';
61: if (seconds < 10)
62: cout << '0';
63: cout << seconds;
64: }
66: private:
67: int hours;
68: int minutes;
69: int seconds;
70: };
74: int main()
75: {
76: cout << endl
77: << "This program illustrates the use of "
78: << "a simple class for representing time. " << endl
79: << "You should study the source code "
80: << "at the same time as the output. " << endl
81: << endl;
83: Time t1;
84: Time t2;
86: t1.Set(11, 59, 50);
87: t2.Set(12, 0, 0);
89: t1.Display(); cout << endl;
90: t2.Display(); cout << endl;
92: cout << endl;
94: for (int i = 1; i <= 11; i++)
95: {
96: t1.Display(); cout << endl;
97: t1.Increment();
98: }
100: cout << endl;
102: return 0;
103: }