Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Time {
  6. int h, m, s;
  7. public:
  8. Time() { h = 0; m = 0; s = 0; }
  9. Time(int h, int m, int s) { SetTime(h, m, s); }
  10. void SetTime(int h1, int m1, int s1);
  11. int GetHours() const { return h; }
  12. int GetMinutes() const { return m; }
  13. int GetSeconds() const { return s; }
  14. Time operator+(Time t2);
  15. Time &operator+=(Time t2); // returning reference suppress copying...
  16. Time &operator++();
  17. Time operator++(int); // To support postfix ++
  18. Time &operator--();
  19. Time operator--(int); // To support postfix --
  20. friend ostream &operator<<(ostream &midheta, Time t);
  21. };
  22.  
  23. void Time::SetTime(int h1, int m1, int s1) { // Better solution (faster)
  24. int total = 3600 * h1 + 60 * m1 + s1; // but more complicated
  25. h = (total / 3600) % 24;
  26. m = (total % 3600) / 60;
  27. s = (total % 3600) % 60; // Even total % 60 will work too...
  28. }
  29.  
  30. ostream &operator<<(ostream &midheta, Time t) {
  31. if(t.h < 10) midheta << "0";
  32. midheta << t.h << ":" ;
  33. if(t.m < 10) midheta << "0";
  34. midheta << t.m << ":";
  35. if(t.s < 10) midheta << "0";
  36. midheta << t.s;
  37. return midheta;
  38. }
  39.  
  40. Time Time::operator +(Time t2) {
  41. return Time(h + t2.h, m + t2.m, s + t2.s);
  42. }
  43.  
  44. Time &Time::operator +=(Time t2) {
  45. SetTime(h + t2.h, m + t2.m, s + t2.s);
  46. return *this;
  47. }
  48.  
  49. Time &Time::operator++() {
  50. SetTime(h, m, s + 1);
  51. return *this;
  52. }
  53.  
  54. Time Time::operator++(int) {
  55. Time old(*this);
  56. SetTime(h, m, s + 1);
  57. return old; // Returns the old value!
  58. }
  59.  
  60. Time &Time::operator--() {
  61. SetTime(h, m, s - 1);
  62. return *this;
  63. }
  64.  
  65. Time Time::operator--(int) {
  66. Time old(*this);
  67. SetTime(h, m, s - 1);
  68. return old; // Returns the old value!
  69. }
  70.  
  71. int main() {
  72. Time t1(7, 25, 47), t2(5, 43, 29);
  73. Time t3 = t1 + t2;
  74. cout << t3 << endl;
  75. t1 = ++t3; // This syntax i supported too!
  76. t1 = t3++;
  77. ++t3;
  78. t3 += t2;
  79. cout << t3 << endl;
  80. --t3;
  81. cout << t3 << endl;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement