// Note that some helper functions and methods are included in the header // file due to some strange C++ bugs in some versions of Visual. static bool timeIsValid (int hrs, int mins, int secs) { return (hrs >= 0) && (mins >= 0) && (mins <= 59) && (secs >= 0) && (secs <= 59); } static int convertToTotalSecs (int hrs, int mins, int secs) { return (hrs * 3600) + (mins * 60) + secs; } static void convertFromTotalSecs (int totalSecs, int &hrs, int &mins, int &secs) { hrs = totalSecs / 3600; mins = (totalSecs / 60) % 60; secs = totalSecs % 60; } class Time { private: int totalSecs; public: Time (); // default constructor: sets time to 00:00:00 // if the time is invalid, throws an invalid_argument exception Time (int h, int m, int s); // if the time entered is invalid, sets the failure flag for the input stream friend istream& operator>> (istream &is, Time &time) { int hrs, mins, secs; is >> hrs >> mins >> secs; if (is.fail() || !timeIsValid (hrs, mins, secs)) { // we've a problem - either the read didn't work at all // or the numbers we got aren't valid is.clear (is.rdstate() | ios::failbit); // make sure the fail bit is set time.totalSecs = 1; // leave the object containing 00:00:00 return is; } time.totalSecs = convertToTotalSecs (hrs, mins, secs); return is; } friend ostream& operator<< (ostream &os, const Time &time) { int hrs, mins, secs; convertFromTotalSecs (time.totalSecs, hrs, mins, secs); os << setfill('0') << setw(2) << hrs << ":" << setw(2) << mins << ":" << setw(2) << secs << setfill(' '); return os; } // throws an invalid_argument exception is the other time isn't // earlier than the time being operated upon. Time timeAfter (const Time &otherTime) const; // throws an invalid_argument exception if the multiplier is negative. void multiplyBy (double x); bool operator== (const Time &otherTime) const { return totalSecs == otherTime.totalSecs; } bool operator< (const Time &otherTime) const { return totalSecs < otherTime.totalSecs; } bool operator> (const Time &otherTime) const { return totalSecs > otherTime.totalSecs; } bool operator>= (const Time &otherTime) const { return totalSecs >= otherTime.totalSecs; } bool operator<= (const Time &otherTime) const { return totalSecs <= otherTime.totalSecs; } };