myFunction.h
#ifndef MYFUNCTION_H_INCLUDED//preprocessor(预处理)
#define MYFUNCTION_H_INCLUDED
class Time
{
public:
//Time();//default constructor
Time(unsigned int = 1, unsigned int = 2, unsigned int = 3);//default constructor
void setTime(unsigned int, unsigned int, unsigned int);
void printUniversal();
void printStandard();
private:
unsigned int hour;
unsigned int minute;
unsigned int second;
};
#endif // MYFUNCTION_H_INCLUDED
Time.cpp
#include <iostream>
#include <iomanip>
#include "myFunction.h"
using namespace std;
/*Time::Time()
{
setTime(0,0,0);
}*/
Time::Time(unsigned int h, unsigned int m, unsigned int s)
{
setTime(h, m, s);
}
void Time::setTime(unsigned int /*hour*/h, unsigned int /*minute*/m, unsigned int /*second*/s)
{
//Time::hour=hour;
//Time::minute=minute;
//Time::second=second;
hour = (h>=0 && h<24)? h : 0;
minute = (m>=0 && m<60)? m : 0;
second = (s>=0 && s<60)? s : 0;
}
void Time::printStandard()
{
cout << setfill('0') << setw(2) << (hour % 12) << ":" <<setw(2) << minute << ":" << setw(2) << second << ((hour < 12)? " AM" : " PM") << endl;
}
void Time::printUniversal()
{
cout << setfill('0') << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second << endl;
}
main.cpp
#include <iostream>
#include "myFunction.h"
using namespace std;
int main()
{
Time t1;
Time t2(10);
Time t3(20, 30);
Time noon(12, 0, 0);
Time *tptr;
noon.printStandard();
t1.printStandard();
t2.printStandard();
t3.printStandard();
t1.setTime(21, 36, 39);
cout << "t1 " << endl;
t1.printUniversal();
t1.printStandard();
tptr = &t1;
tptr->printStandard();
//t1.hour = 11;
return 0;
}