// timeclass2.cc #include #include // for stringstream below #include using namespace std; class Time { private: int Hours; // 0 to 23 int Minutes; // 0 to 59 string StringForm; // time converted to a string public: Time() { Hours = Minutes = 0; } Time(int hrs, int mins) :Hours(hrs),Minutes(mins) { } void printTime() { cout << Hours << " hours and " << Minutes << " minutes" << endl; } // do any rollovers necessary on hours or minutes void TimeCheck() { if (Minutes > 59) { Minutes = 0; ++Hours; } if (Minutes < 0) { Minutes = 59; --Hours; } if (Hours > 23) Hours = 0; if (Hours < 0) Hours = 23; } // prefix ++ operator, i.e., ++myTime Time& operator ++ () { ++Minutes; TimeCheck(); return *this; // don't want to make a new object } // prefix -- operator, i.e., --myTime Time& operator -- () { --Minutes; TimeCheck(); return *this; // don't want to make a new object } // postfix ++ operator, i.e., myTime++ // here we need to return the state before increment Time operator ++ (int) { Time TmpTime(Hours, Minutes); // make a backup ++Minutes; TimeCheck(); return TmpTime; } // postfix -- operator, i.e., myTime-- // here we need to return the state before decrement Time operator -- (int) { Time TmpTime(Hours, Minutes); // make a backup --Minutes; TimeCheck(); return TmpTime; } operator const char*() { ostringstream out; // stringstream lets us build strings out << Hours << ":" << Minutes; StringForm = out.str(); // hold this as member data so it and the // char* to it won't disappear at end // of this function return StringForm.c_str(); // get C-style const char* from string } }; int main() { Time T1(0, 0); --T1; cout << "Time is " << T1 << endl; }