Answer to Question #318385 in C++ for Sid

Question #318385

Create a class called time that has separate int member data for hours, minutes, and

seconds. One constructor should initialize this data to 0, and another should initialize it

to fixed values. Another member function should display it, in 11:59:59 format. The final

member function should add two objects of type time passed as arguments. A main() program should create two initialized time objects (should they be const?) and one that isn’t initialized. Then it should add the two initialized values together, leaving the result in the third time variable. Finally it should display the value of this third variable. Make appropriate member functions const.



1
Expert's answer
2022-03-26T02:39:32-0400
#include <iostream>
#include <iomanip>
using namespace std;


class Time {
    int hours;
    int minutes;
    int seconds;


public:
    Time();
    Time(int h, int m, int s);
    void display() const;
    void add(Time& t1, Time& t2);
};


Time::Time() 
    : hours(0), minutes(0), seconds(0)
{}


Time::Time(int h, int m, int s) 
    : hours(h), minutes(m), seconds(s)
{}


void Time::display() const {
    cout << hours << ':' << setfill('0') << setw(2)
         << minutes << ':' << setw(2) << seconds << endl;
}


void Time::add(Time& t1, Time& t2) {


    seconds = t1.seconds + t2.seconds;
    minutes = (seconds >= 60 ? 1 : 0);
    seconds %= 60;


    minutes += t1.minutes + t2.minutes;
    hours = (minutes >= 60 ? 1 : 0);
    minutes %= 60;


    hours += t1.hours + t2.hours;
    hours %= 24;
}


int main() {
    Time t1(10, 20, 30);
    Time t2(1, 50, 45);
    Time t3;


    t3.add(t1, t2);
    t3.display();


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog