fork download
  1. // Fig. 9.9: Time.cpp
  2. // Member-function definitions for class Time.
  3. #include <iostream>
  4. #include <iomanip>
  5. #include <stdexcept>
  6. #include "Time.h" // include definition of class Time from Time.h
  7. using namespace std;
  8.  
  9. // Time constructor initializes each data member to zero
  10. Time::Time( int hour, int minute, int second )
  11. {
  12. setTime( hour, minute, second ); // validate and set time
  13. } // end Time constructor
  14.  
  15. // set new Time value using universal time
  16. void Time::setTime( int h, int m, int s )
  17. {
  18. setHour( h ); // set private field hour
  19. setMinute( m ); // set private field minute
  20. setSecond( s ); // set private field second
  21. } // end function setTime
  22.  
  23. // set hour value
  24. void Time::setHour( int h )
  25. {
  26. if ( h >= 0 && h < 24 )
  27. hour = h;
  28. else
  29. throw invalid_argument( "hour must be 0-23" );
  30. } // end function setHour
  31.  
  32. // set minute value
  33. void Time::setMinute( int m )
  34. {
  35. if ( m >= 0 && m < 60 )
  36. minute = m;
  37. else
  38. throw invalid_argument( "minute must be 0-59" );
  39. } // end function setMinute
  40.  
  41. // set second value
  42. void Time::setSecond( int s )
  43. {
  44. if ( s >= 0 && s < 60 )
  45. second = s;
  46. else
  47. throw invalid_argument( "second must be 0-59" );
  48. } // end function setSecond
  49.  
  50. // return hour value
  51. int Time::getHour()
  52. {
  53. return hour;
  54. } // end function getHour
  55.  
  56. // return minute value
  57. int Time::getMinute()
  58. {
  59. return minute;
  60. } // end function getMinute
  61.  
  62. // return second value
  63. int Time::getSecond()
  64. {
  65. return second;
  66. } // end function getSecond
  67.  
  68. // print Time in universal-time format (HH:MM:SS)
  69. void Time::printUniversal()
  70. {
  71. cout << setfill( '0' ) << setw( 2 ) << getHour() << ":"
  72. << setw( 2 ) << getMinute() << ":" << setw( 2 ) << getSecond();
  73. } // end function printUniversal
  74.  
  75. // print Time in standard-time format (HH:MM:SS AM or PM)
  76. void Time::printStandard()
  77. {
  78. cout << ( ( getHour() == 0 || getHour() == 12 ) ? 12 : getHour() % 12 )
  79. << ":" << setfill( '0' ) << setw( 2 ) << getMinute()
  80. << ":" << setw( 2 ) << getSecond() << ( hour < 12 ? " AM" : " PM" );
  81. } // end function printStandard
  82.  
  83. void Time::tick(Time * T)
  84. {
  85. T->setSecond(T->getSecond()+1);
  86. }
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty