Create a class Time with data members – Hours(int), Minutes(int) and Seconds(int). Include two
constructors – (i) to initialize the data members to zero, and (ii) to initialize the data members with
the values passed as arguments. Include two member functions – (i) AddTime() to add two objects
passed as parameters and set the invoking object with this result (ii) DispTime() to display the time
in the format hh:mm:ss. The main() program should create two initialized Time objects and one that
is not initialized. Add the two initialized values leaving the result in the third Time object. Display the
values of the third object.
#include <iostream>
using namespace std;
//Implement class Time
class Time
{
private:
int hours;//Hours
int minutes;//Minutes
int seconds;//Second
public:
//Default constrcuctor(i)
Time()
{
this->hours = 0;
this->minutes = 0;
this->seconds = 0;
}
//(ii) Parametrazed constructor
Time(int _h, int _m, int _s)
{
this->hours = _h;
this->minutes = _m;
this->seconds = _s;
}
//Function member
Time AddTime(const Time& a, const Time& b)
{
int _s = (a.seconds + b.seconds)%60;
int _m = (a.minutes + b.minutes + (a.seconds + b.seconds) / 60) % 60;
int _h = (((a.minutes + b.minutes + (a.seconds + b.seconds) / 60)) / 60 + a.hours + b.hours) % 24;
return Time(_h, _m, _s);
}
void DispTime()
{
cout << hours / 10 << hours % 10 << ":" << minutes / 10 << minutes % 10 << ":" << seconds / 10 << seconds % 10 << endl;
}
};
int main()
{
int h, m, s;
cout << "Please enter hour First object: ";
cin >> h;
cout << "Please enter minutes First object: ";
cin >> m;
cout << "Please enter seconds First object: ";
cin >> s;
Time one(h, m, s);
cout << "Please enter hour Second object: ";
cin >> h;
cout << "Please enter minutes Second object: ";
cin >> m;
cout << "Please enter seconds Second object: ";
cin >> s;
Time two(h, m, s);
Time th ;
th = th.AddTime(one, two);
th.DispTime();
return 0;
}
Comments
Leave a comment