Q#2). Create a class called Time that has data members to represent hours, minutes and seconds.
Provide the following member functions:-
1. To assign initial values to the Time object.
2. To display a Time object in the form of hh:mm:ss {0 to 24 hours}
3. To add 2 Time objects (the return value should be a Time object)
4. To subtract 2 Time objects (the return value should be a Time object)
5. To compare 2 time objects and to determine if they are equal or if the first is greater or smaller than
the second one.
#include<iostream>
using namespace std;
// Create a class called Time that has data members to represent hours, minutes and seconds
class Time {
  private:
    int hours;
    int minutes;
    int seconds;
  public:
  //assign initial values to the Time object
    Time(){Â
    hours = 0;
    minutes = 0;
    seconds = 0;
    }
    Time(int hrs, int min, int sec) {
    hours = hrs;
    minutes = min;
    seconds = sec;
    }
    //display a Time object in the form of hh:mm:ss {0 to 24 hours}
    void display(){
      cout << hours << ":" << minutes << ":" << seconds << endl;
    }Â
    //To add 2 Time objects (the return value should be a Time object)
    int getHours(){
      return hours;
    }
    int getMinutes(){
      return minutes;
    }
    int getSeconds(){
      return seconds;
    }
    Time add(Time t1, Time t2) {
      int hours2 = t1.getHours() + t2.getHours();
      if (hours2 > 23) {
      hours2 -= 24;
      }
      int minutes2 = t1.getMinutes() + t2.getMinutes();
      if (minutes2 > 59) {
      minutes2 -= 60;
      hours2 += 1;
      }
      int seconds2 = t1.getSeconds() + t2.getSeconds();
      if (seconds2 > 59) {
      seconds2 -= 60;
      minutes2 += 1;
      }
      Â
      Time time3(hours2, minutes2, seconds2);
      return time3;
    };
  //To subtract 2 Time objects (the return value should be a Time object)
    Â
  Time sub( Time t1, Time t2) {
    int nDiff(t1.getHours()*3600 + t1.getHours()*60 - (t2.getHours()*3600 + t2.getMinutes()*60));
  Â
    int nHours(nDiff/3600);
    int nMins((nDiff%3600)/60);
    int nSec((nDiff%3600)%60);
    return Time(nHours, nMins,nSec);
  } Â
  //To compare 2 time objects and to determine if they are equal or if the first is greater or smaller than
  //the second one.
  bool operator == ( Temp& t) {
     return this->hours == t.hours;
  } Â
};
int main() {
  Time t1(20, 50, 30);
  Time t2(10, 30, 43);
  Â
  t1.display();
  t2.display();
  Â
  Time t3=t1.add(t1,t2);
  t3.display();
  // cout<<"\nAfter ADD: "<<t1.add(t1, t2);
  return 0;
}
Comments
Leave a comment