//BetterTime.cpp //!! marks lines or sections that are new //!! No #ifndefs etc. here in cpp file #include //cout using namespace std; #include"BetterTime.h" //implementation of class functions bool Time::Set12(int hr, int min, char ap) //Sets time when given hours and minutes //in 12 hour format. //When an invalid time //is entered, sets time to noon and //returns false. //noon is 12:00 am, midnight is 12:00 pm. { //set to a valid time, noon hour=12; minute=0; if ((hr<1) || (min<0) || (min>59) || (hr>12)) // || is OR return 0; //0 is false if ((ap!='a') && (ap!='A') && (ap!='p') && (ap!='P')) // && is AND // symbols in single quotes // are characters return 0; //Got here only if valid time if ((ap=='a') || (ap=='A')) // am // == is comparison EQUAL hour=hr; // = is ASSIGNMENT else // pm hour=hr+12; minute=min; if (hour == 24) hour = 0; return 1; //any nonzero integer is true } //end set12 bool Time::Set24(int hr, int min) //Sets time when given hours and minutes //in 24 hour format. //When an invalid time //is entered, sets time to noon and //returns false. //noon is 12:00, midnight is 0:00. //set default time { hour = 12; minute = 0; if ((hr<0) || (min<0) || (min>59) || (hr>=24)) // || is OR return 0; //0 is false hour=hr; minute=min; return 1; //any nonzero integer is true } //end set24 int Time::GetMinutes() {return minute;} int Time::GetHour12() { if ((hour<=12) && (hour>=1)) return hour; else if (hour==0) return 12; else return hour-12; } int Time::GetHour24() {return hour;} char Time::GetAMPM() { if (hour>0 && hour<=11) return 'A'; else if ((hour==12) && (minute==0)) return 'A'; else if ((hour==0) && (minute>0)) return 'A'; else return 'P'; } //end GetAMPM void Time::Display12() { cout << GetHour12() << ':' << minute << ' ' << GetAMPM() << 'M'; return; } //end Display12 //!! //Slightly nicer display void Time::Display24() { cout << hour << ':'; if (minute<10) cout << 0; cout << minute; } //!! -------------- //All that follows is new //implementation of operations for the time class //Notice the answer is the calling object itself, not //a newly created Time Time Time::operator++() //prefix increment operator { int min=minute; int hr=hour; if (++min>59) { ++hr; min=0; } if (hr==24) hr=0; //next day Set24(hr,min); return *this; //*this is the object that called this function } //end operator++ Time Time::operator-(Time right) { Time result; //need a place for the answer int min, hr; min = GetMinutes() - right.GetMinutes(); hr = GetHour24() - right.GetHour24(); if (min < 0) { min=min+60; --hr; } if (hr < 0) hr+=24; result.Set24(hr, min); return result; } bool Time::operator==(Time right) { return ((GetHour24()==right.GetHour24()) && (GetMinutes()==right.GetMinutes())); }//end operator== bool Time::operator!=(Time right) { return !(*this==right); //note: uses the function operator== //defined above. } //end operator!=