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: void Set(/* in */ int hoursNew,
12: /* in */ int minutesNew,
13: /* in */ int secondsNew);
14: // Pre: 0 <= hoursNew <= 23
15: // 0 <= minutesNew <= 59
16: // 0 <= secondsNew <= 59
17: // Post: Time is set according to the incoming parameters.
18: // Note that this function must be called prior to a call
19: // to any other member function.
21: void Increment();
22: // Pre: The Set function has been called at least once.
23: // Post: Time has been advanced by one second, with
24: // 23:59:59 wrapping around to 0:0:0.
26: void Display() const;
27: // Pre: The Set function has been called at least once.
28: // Post: Time has been output in the form HH:MM:SS.
30: private:
31: int hours;
32: int minutes;
33: int seconds;
34: };
38: int main()
39: {
40: cout << endl
41: << "This program illustrates the use of "
42: << "a simple class for representing time. " << endl
43: << "You should study the source code "
44: << "at the same time as the output. " << endl
45: << endl;
47: Time t1;
48: Time t2;
50: t1.Set(11, 59, 50);
51: t2.Set(12, 0, 0);
53: t1.Display(); cout << endl;
54: t2.Display(); cout << endl;
56: cout << endl;
58: for (int i = 1; i <= 11; i++)
59: {
60: t1.Display(); cout << endl;
61: t1.Increment();
62: }
64: cout << endl;
66: return 0;
67: }
70: //******************************************************************
71: void Time::Set(/* in */ int hoursNew,
72: /* in */ int minutesNew,
73: /* in */ int secondsNew)
74: // Pre: 0 <= hoursNew <= 23
75: // 0 <= minutesNew <= 59
76: // 0 <= secondsNew <= 59
77: // Post: Time is set according to the incoming parameters.
78: // Note that this function MUST have been called prior to
79: // any call to *any* of the other member functions.
80: {
81: hours = hoursNew;
82: minutes = minutesNew;
83: seconds = secondsNew;
84: }
88: //******************************************************************
89: void Time::Increment()
90: // Pre: The Set function has been called at least once.
91: // Post: Time has been advanced by one second, with
92: // 23:59:59 wrapping around to 0:0:0.
93: {
94: seconds++;
95: if (seconds > 59)
96: {
97: seconds = 0;
98: minutes++;
99: if (minutes > 59)
100: {
101: minutes = 0;
102: hours++;
103: if (hours > 23)
104: hours = 0;
105: }
106: }
107: }
111: //******************************************************************
112: void Time::Display() const
113: // Pre: The Set function has been called at least once.
114: // Post: Time has been output in the form HH:MM:SS.
115: {
116: if (hours < 10)
117: cout << '0';
118: cout << hours << ':';
119: if (minutes < 10)
120: cout << '0';
121: cout << minutes << ':';
122: if (seconds < 10)
123: cout << '0';
124: cout << seconds;
125: }