|
ex3-4.cpp - Example 3-4 The Clock class |
// File: ex3-4.cpp - the clock class
#include <iostream>
using namespace std;
class Clock
{
private:
int hours;
int minutes;
int seconds;
public:
void set(int h, int m, int s)
{hours = h; minutes = m; seconds = s; return;} // inline
void increment(void);
void display(int=0) const;
};
void Clock::increment (void)
{
seconds++;
minutes += seconds/60;
hours += minutes/60;
seconds %= 60;
minutes %= 60;
hours %= 24;
return;
}
void Clock::display(int format) const
{
if (format) { // use format hh:mm:ss AM/PM
cout << (hours % 12 ? hours % 12:12) << ':'
<< (minutes < 10 ? "0" :"") << minutes << ':'
<< (seconds < 10 ? "0" :"") << seconds
<< (hours < 12 ? " AM" : " PM") << endl;
}
else { // use format hh:mm:ss (24 hour time)
cout << (hours < 10 ? "0" :"") << hours << ':'
<< (minutes < 10 ? "0" :"") << minutes << ':'
<< (seconds < 10 ? "0" :"") << seconds << endl;
}
}
int main(void)
{
Clock c;
c.set(23,59,55);
for (int i = 0; i < 10; i++)
{
c.increment();
c.display();
c.display(1);
cout << endl;
}
return 0;
}
CIS27: Programming in C++ Instructor: Joe Bentley