Answer to Question #246953 in C++ for Elena

Question #246953

3 Create a class called 'TIME' that has three integer data members for hours, minutes and seconds, a constructor to initialize the object to some constant

value, member function to add two TIME objects, member function to

display time in HH:MM:SS format. Write a main function to create two

TIME objects, add them and display the result in HH:MM:SS format.


1
Expert's answer
2021-10-05T10:16:09-0400
#include <iostream>
#include <iomanip>
using namespace std;

class TIME {
public:
    TIME(int h=0, int m=0, int s=0);
    TIME operator+(const TIME& t) const;
    void display(ostream& os=cout) const;
private:
    int hour;
    int min;
    int sec;
};

TIME::TIME(int h, int m, int s) {
    sec = s % 60;
    int mm = (m + s/60);
    min =  mm % 60;
    hour = (h + mm/60) % 24;
}

TIME TIME::operator+(const TIME& t) const
{
    TIME res(hour+t.hour, min+t.min, sec+t.sec);
    return res;
}

void TIME::display(ostream& os) const
{
    os << setw(2) << setfill('0') << hour << ":";
    os << setw(2) << setfill('0') << min << ":";
    os << setw(2) << setfill('0') << sec;
}

ostream& operator<<(ostream& os, const TIME& t) {
    t.display(os);
    return os;
}

int main()
{
    TIME t1(10, 30, 0);
    TIME t2(20, 45, 5);

    cout << t1 << " + " << t2 << " = " << t1 + t2 << endl;

    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
APPROVED BY CLIENTS