Answer to Question #235108 in C++ for SOM

Question #235108

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-09-10T18:54:05-0400
#include <iostream>


using namespace std;


class Time {
    private:
        int h;
        int m;
        int s;
    public:
        Time(){
            this->h = 0;
            this->m = 0;
            this->s = 0;
        };
        Time(int h, int m, int s) {
            this->h = h;
            this->m = m;
            this->s = s;
        };
        int getHours(){
        return this->h;
        };
        int getMinutes(){
        return this->m;
        };
        int getSeconds() {
        return this->s;
        };
        void display(){
        cout << h << ":" << m << ":" << s << endl;
        };
        Time add(Time time1, Time time2) {
        int hoursAdd = time1.getHours() + time2.getHours();
        if (hoursAdd > 23) {
        hoursAdd -= 24;
        }
        int minutesAdd = time1.getMinutes() + time2.getMinutes();
        if (minutesAdd > 59) {
        minutesAdd -= 60;
        hoursAdd += 1;
        }
        int secondsAdd = time1.getSeconds() + time2.getSeconds();
        if (secondsAdd > 59) {
        secondsAdd -= 60;
        minutesAdd += 1;
        }
        
        Time time3(hoursAdd, minutesAdd, secondsAdd);
        return time3;
        };
};




int main() {
    Time t1(11,35,23);
    Time t2(12, 22, 36);
    Time t3;
    t3 = t3.add(t1, t2);
    t1.display();
    t2.display();
    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
APPROVED BY CLIENTS