Reputation: 13
class Time {
private:
int hour = 0;
int minute = 0;
public:
Time(int hour, int minute);
void setHour(int hour);
void setMinute(int minute);
int getHour();
int getMinute();
void print();
void advance();
};
Time::Time(int h, int m) // DONE
{
hour = h;
minute = m;
if (hour > 23)
{
hour = 0;
}
if (minute > 59)
{
minute = 0;
}
}
void Time::setHour(int h) // DONE
{
if (h > 23)
{
hour = 0;
}
else
{
hour = h;
}
}
void Time::setMinute(int m) // DONE
{
if (m > 59)
{
minute = 0;
}
else
{
minute = m;
}
}
int Time::getHour() // DONE
{
return hour;
}
int Time::getMinute() // DONE
{
return minute;
}
void Time::print() // DONE
{
string period;
string minutezero;
if (hour > 12)
{
hour = hour - 12;
period = "PM";
}
else if (hour < 13)
{
period = "AM";
}
if (hour == 0)
{
hour = 12;
period = "AM";
}
if (minute < 10)
{
cout << hour << ":" << "0" << minute << " " << period;
}
else if (minute > 9)
{
cout << hour << ":" << minute << " " << period;
}
}
void Time::advance() // DONE
{
minute = minute + 1;
if (minute == 60)
{
minute = 0;
hour = hour + 1;
}
if (hour == 24)
{
hour = 0;
}
}
On my int main function, I would like to create an array like Time t[5] that will hold 5 time objects. How would I code this?
Here is what my module says word for word:
**Modify Time class to set up constructor(s) so the following Time objects can be created in the driver. Set up a Time array as specified below and print the times in the driver as well (can add to regular version and submit one version).
Time t1; // hour: 0, minute: 0, 12:00 AM
Time t2(8); // hour: 8, minute: 0, 8:00 AM
Time t3(13, 30); // hour: 13, minute: 30, 1:30 PM
Time t4(25, 5); // hour: 0, minute: 5, 12:05 AM
Time t4(12, 60); // hour: 12, minute: 0, 12:00 PMI**
Upvotes: 0
Views: 50
Reputation: 38341
For example
#include <algorithm>
#include <vector>
#include <iterator>
int main(){
std::vector<Time> t;
std::fill_n(std::back_inserter(t), 5, Time(0, 0));
}
Or use pointers
std::array<std::unique_ptr<Time>, 5> t; // std::unique_ptr<Time> t[5];
According to the requirement Time t1; // hour: 0, minute: 0, 12:00 AM
you have to add and implement the default constructor Time::Time()
, or yet better if you make only one Time::Time(int hour = 0, int minute = 0)
with default parameter values.
A bit update:
class Time {
private:
int hour = 0;
int minute = 0;
public:
Time(int hour = 0, int minute = 0);
// skipped
Upvotes: 0
Reputation: 36
As paddy pointed out in a comment you need a default constructor that would look something like this:
Time::Time() : hour(0), minute(0) { }
And you also need a constructor with only the hour as a parameter
Time::Time(int h) : hour(h), minute(0) {
if (hour > 23) hour = 0;
}
After that your class would look something like this
public:
Time();
Time(int h);
Time(int hour, int minute);
void setHour(int hour);
...
Upvotes: 1