Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a class named Time that would be used to store a time expressed in hours,

ID: 3689694 • Letter: C

Question

Create a class named Time that would be used to store a time expressed in hours, minutes and seconds. Your class should have all the appropriate constructors and accessor methods. In addition, there should be a method defined as:

Time::add(const Time & t)

This method should add the time t to the object it is called from. Time.h should work with times.cpp

// times.cpp

#include <iostream>
#include "Time.h"

using namespace std;

int main(int argc, const char * argv[])
{
Time myTime = Time(10, 46, 32);
Time anotherTime = Time(2, 25, 50);

myTime.add(anotherTime);

cout << myTime.getHours() << " : " << myTime.getMinutes() << " : " << myTime.getSeconds() << endl;
return 0;
}

Explanation / Answer

main.cpp

#include <iostream>
#include "Time.h"

using namespace std;

int main(int argc, const char * argv[])
{
    Time myTime = Time(10, 46, 32);
    Time anotherTime = Time(2, 25, 50);
  
    myTime.add(anotherTime);
  
    cout << myTime.getHours() << " : " << myTime.getMinutes() << " : " << myTime.getSeconds() << endl;
    return 0;
}

Time.h
#ifndef _MYTIME_H_
#define _MYTIME_H_

#include <ctime>

class Time
{
    int h;
    int m;
    int s;

public:
    Time()
    {
        std::time_t t = std::time(NULL);
        std::tm* tm = std::localtime ( &t ); // returns pointer to a static object
        h = tm->tm_hour;
        m = tm->tm_min;
        s = tm->tm_sec;
    }

    Time(int h, int m, int s)
       : h(h), m(m), s(s)
    {
    }

    int getHours()
    {
       return h;
    }

    int getMinutes()
    {
       return m;
    }

    int getSeconds()
    {
       return s;
    }

    void add(const Time& t)
    {
       // seconds
       int rs = s + t.s;
       s = rs % 60;

       // minutes
       int rm = m + t.m + (rs/60);
       m = rm % 60;

       // hours
       int rh = h + t.h + (rm/60);
       h = rh % 24;
    }
};

#endif

sample output

13: 12: 22

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote