Question
Problem: Add a conversion operator to the code for converting a time12 object to a time24 object and test it in the main() function. *
Problem:
Add a conversion operator to the code for converting a time12 object to a time24 object and test it in the main() function.
* Notes for this problem *
To use class b in class a but class b is defined after class a, you need to have the declaration of class b ( i.e. class b;) before class a.
Since there are no seconds in the time12 class, the seconds will be treated as zero in the conversion.
Conversion operator should be added to the source class.
One-arg constructor should be added to the destination class.
Code:
/*
* Two kinds of time case: conversion between objects of different classes:
* conversion operator in the source object
*/
#include
#include
#include
using namespace std;
/** civilian time */
class time12
{
private:
bool pm; // true: pm; false: am
int hrs; // 1 - 12
int mins; // 0 - 59
public:
time12() : pm(true), hrs(0), mins(0) {} // no-arg constructor
time12(bool ap, int h, int m) : pm(ap), hrs(h), mins(m) {} // three-arg constructor
void display()
{
cout << hrs << ':';
cout << setw(2) << setfill('0') << mins << ' ' ;;
string am_pm = pm ? "p.m. " : "a.m. ";
cout << am_pm;
}
};
/** military time */
class time24
{
private:
int hours; // 0 - 23
int minutes; // 0 - 59
int seconds; // 0 - 59
public:
time24() : hours(0), minutes(0), seconds(0) {} // no-arg constructor
time24(int h, int m, int s) : hours(h), minutes(m), seconds(s) {} // three-arg constructor
void display()
{
cout << setw(2) << setfill('0') << hours << ':';
cout << setw(2) << setfill('0') << minutes << ':';
cout << setw(2) << setfill('0') << seconds;
}
operator time12() const; // conversion operator
};
time24::operator time12() const
{
int hrs24 = hours;
bool pm = (hrs24<12) ? false : true;
int roundmins = seconds < 30 ? minutes : minutes+1; // round seconds
if (roundmins == 60) // carry mins
{
roundmins = 0;
++hrs24;
if (hrs24 == 12 || hrs24 == 24) pm = (pm==true) ? false : true; // carry hrs? yes toggle pm/am
}
int hrs12 = (hrs24 > 13) ? hrs24-12 : hrs24;
if (hrs12 == 0) {hrs12 = 12; pm = false;}
return time12(pm, hrs12, roundmins);
}
int main()
{
int h, m, s;
cout << "enter hour (0-23): "; cin >> h;
cout << "enter minutes (0-59): "; cin >> m;
cout << "enter seconds (0-59): "; cin >> s;
time24 t24(h, m, s);
cout << "24-hour time: "; t24.display(); cout << endl;
time12 t12 = t24;
cout << "12-hour time: "; t12.display(); cout << endl;
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started