-
Timer OOP Method (I/O)
Hi, here is an OOP based time program which is although static and works on input or initializing variables here for u:
Code:
time1.h
#pragma once
class time1
{
public:
time1(int=0, int=0, int=0);
void setTime(int, int, int);
void printMilitary();
void printStandard();
~time1(void);
private:
int hour, minute, second;
};
Code:
time1.cpp
#include "time1.h"
#include <iostream>
using namespace std;
time1::time1(int hr, int min, int sec)
{
setTime(hr, min, sec);
}
void time1::setTime(int h, int m, int s)
{
hour= (h>=0 && h<24) ? h:0;
minute=(m>=0 && m<60) ? m:0;
second=(s>=0 && s<60) ? s:0;
}
void time1::printMilitary()
{
cout<< (hour<10 ? "0" : "") << hour << ":"
<< (minute <10 ? "0" : "")<<minute;
}
void time1::printStandard()
{
cout<< ((hour==0 || hour==12) ? 12 : hour % 12)
<< ":" << (minute < 10 ? "0" : "") << minute
<< ":" << (second < 10 ? "0" : "") <<second
<<(hour < 12 ? " AM" : " PM");
}
time1::~time1(void)
{
}
Code:
source file source.cpp
#include<iostream>
#include"time1.h"
using namespace std;
void main()
{
time1 t1, t2(2), t3(21, 34), t4(12,25, 42), t5(27,74,99);
cout<< "Default Time: \n";
t1.printMilitary();
cout<<endl;
t1.printStandard();
cout<< "\n\nHour input, minutes and seconds are default: \n";
t2.printMilitary();
cout<<endl;
t2.printStandard();
cout<<"\n\nhours and minutes specified, seconds default: \n";
t3.printMilitary();
cout<<"\n";
t3.printStandard();
cout<<"\n\nEverything is specified: \n";
t4.printMilitary();
cout<<endl;
t4.printStandard();
cout<<"\n\nall invalid values given: \n";
t5.printMilitary();
cout<<endl;
t5.printStandard();
cout<<endl;
system("pause");
}
Any Question, feel free to ask!
-
O_o
Well, there is no timer in that code so the label is misleading.
The design is also not "OOP".
You have certainly hit "Oh! My! God! OOPS!" for critical damage: you just taken two exceedingly simple functions, put them in a class, and moved the parameters to the constructor for absolutely no reason.
I don't really have a question. ;_;
Soma
-
I have three questions for you:
- Why are you using void main?
- Why are you not following the recommended advice in this article?
- Why are you not rejecting incorrect input (eg inputting hours > 24 sets it to 0)?