Create a class called Time and then write a driver program to test your class by
ID: 3820669 • Letter: C
Question
Create a class called Time and then write a driver program to test your class by creating some objects and performing various operations. Your program must have at least three files: a Time header file (Time.h), a Time implementation file (Time.cpp), and an application file (TimeDriver.cpp). The class has only two int data members hour and minute, with the hour defaults to 0 and the minute defaults to 0 (i.e., the constructor has two default arguments, hour and then minute in that order; note that the default time is 00:00 or 12:00 AM). The hour must be between 0 and 23 and the minute must be between 0 and 59 so validation is needed. Provide the following public member functions:
Constructor (two default parameters); must verify that hour is between 0 and 23 and default to 0 if needed; must verify that minute is between 0 and 59 and default to 0 if needed.
Time(int h = 0, int m = 0);
Setting the hour (must verify that the value is between 0 and 23 and keep current hour if applicable). void setHour(int h);
Setting the minute (must verify that the value is between 0 and 59 and keep current minute if applicable). void setMinute(int m);
Returning the hour. int getHour();
Returning the minute. int getMinute();
Printing the time in AM/PM format (like 1:05 AM, but not 1:5 AM). void print();
Include and use an array of Time objects and a Time pointer in your program
Explanation / Answer
Time.h:
#ifndef TIME_H
#define TIME_H
class Time
{
private :
int hour;
int minute;
public :
Time(int h = 0, int m = 0);
void setHour(int h);
void setMinute(int m);
int getHour();
int getMinute();
void print() const;
};
#endif
Time.cpp:
#include <iostream>
#include <iomanip>
#include "Time.h"
using namespace std;
Time ::Time(int h, int m)
{
if(h>=0 && h<=23)
hour = h;
else
hour=0;
if(m>=0 && m<=59)
minute = m;
else
minute=0;
}
void Time :: setHour(int h)
{
if(h>=0 && h<=23)
hour = h;
else
hour=0;
}
void Time :: setMinute(int m)
{
if(m>=0 && m<=59)
minute = m;
else
minute=0;
}
int Time :: getHour()
{
return hour;
}
int Time :: getMinute()
{
return minute;
}
void Time :: print() const
{
if(hour==0)
cout<<"12:";
else if(hour < 13)
cout<< hour << ":";
else
cout<<hour-12<< ":";
cout<< setw(2) << setfill('0') << minute << " ";
if(hour<12)
cout<<"AM ";
else
cout<<"PM ";
}
TimeDriver.cpp:
#include <iostream>
#include "Time.h"
using namespace std;
int main()
{
Time t[10];
Time *tp;
Time t1(12,22);
t[0].print();
t[0].setHour(6);
t[0].setMinute(57);
t[0].print();
t[0].setHour(25);
t[0].print();
tp=&t[0];
tp->print();
t1.print();
cout<<t1.getHour()<<endl;
cout<<t1.getMinute()<<endl;
}
Output:
$ g++ TimeDriver.cpp Time.cpp
$ ./a.out
12:00 AM
6:57 AM
12:57 AM
12:57 AM
12:22 PM
12
22
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.