/********************************************************************************************
example 10 -- clocktime.cpp
using a single member data to handle all three fields
********************************************************************************************/
#include "clocktime.h"
#include <iostream>
using namespace std;
//------- Initialize static class data -------
bool clocktime::AMPM = false;
//------- Enhanced Default Constructor -------
clocktime::clocktime(const int h, const int m, const int s) {
second = 0;
addSecond(s);
addMinute(m);
addHour(h);
}
//------- Manage static class data -------
void clocktime::show24H(const bool& set) {
AMPM = (!set);
}
void clocktime::showAMPM(const bool& set) {
AMPM = set;
}
//------- Retrieve individual entries -------
const int clocktime::getHour() const {
return second / 3600;
}
const int clocktime::getMin() const {
int temp = second % 3600;
return temp / 60;
}
const int clocktime::getSec() const {
return second % 60;
}
//------- Print the object in "pretty" format -------
void clocktime::print(ostream& out) const {
if (AMPM) {
if ((getHour() > 0) && (getHour() < 10))
out << '0';
if (getHour() == 0)
out << 12;
else if (getHour() > 12)
out << getHour() - 12;
else
out << getHour();
}
else {
if (getHour() < 10)
out << '0';
out << getHour();
}
out << ':';
if (getMin() < 10)
out << '0';
out << getMin() << ':';
if (getSec() < 10)
out << '0';
out << getSec();
if (AMPM) {
if (getHour() < 12)
out << " AM";
else
out << " PM";
}
};
//------- "managed" addition functions -------
void clocktime::addHour(const int h) {
addSecond(h * 3600);
}
void clocktime::addMinute(const int m) {
addSecond(m * 60);
}
void clocktime::addSecond(const int s) {
int sum = second + s;
if (sum > -1)
second = (second + s) % (3600 * 24);
else
second = 0;
}
void clocktime::addSame(const clocktime& mt) {
addSecond(mt.second);
}
//------- user-defined operators -------
clocktime clocktime::operator+(const clocktime& mt) const {
clocktime temp;
temp.addSame(*this);
temp.addSame(mt);
return temp;
}
ostream& operator<<(ostream& out, const clocktime& mt) {
mt.print(out);
return out;
}