C++日期類、時間類、日期時間類的設計
DateTimeHeader.h
1.//日期類
2.class Date{
3. public:
4. int day;
5. int month;
6. int year;
7. public:
8. void show();
9. // Date():year(1900),month(1),day(1){}
10. Date(){};
11. void init(int,int,int);
12. // Date operator +(Date&);
13. // Date operator =(Date);
14. Date operator ++();
15. Date operator ++(int);
16.};
17.//時間類
18.class Time{
19. public:
20. int Hour;
21. int Minute;
22. int Second;
23. void show();
24. Time():Hour(12),Minute(0),Second(0){}
25. void init(int x,int y,int z);
26. Time operator +(Time&);
27. Time operator =(Time);
28. Time operator ++();
29.};
30.
31.//時間日期類
32.class Calender{
33. private:
34. Time time;
35. Date date;
36. public:
37. ~Calender();
38. Calender(Time time,Date date);
39. Calender operator +(Calender&);
40. Calender operator =(Calender);
41. Calender operator ++();
42. void show();
};
DateTimeFunction.cpp
1.#include "DateTimeHeader.h"
2.#include<iostream>
3.using namespace std;
4.
5.
6.
7.void Date::init(int y,int m,int d){
8. this->year = (y>1900 && y<=2200) ? y : 1900;
9. this->month = (m>= 1 && m<=12) ? m : 1;
10. this->day = (d>=1 && d<=31) ? d : 1;
11.}
12.
13.void Time::init(int h,int m,int s){
14. this->Hour = (h>=1 && h<=24) ? h : 12;
15. this->Minute = (m>=0 && m<=59) ? m : 0;
16. this->Second = (s>=0 && s<=59) ? s : 0;
17.}
18.
19.void Date::show(){
20. cout<<year<<"年"<<month<<"月"<<day<<"日"<<endl;
21.}
22.
23.void Time::show(){
24. cout<<Hour<<"時"<<Minute<<"分"<<Second<<"秒"<<endl;
25.}
26.
27.void Calender::show(){
28. cout<<"時間是:";
29. time.show();
30. cout<<"日期是:";
31. date.show();
32.}
33.
34.Time Time::operator +(Time& t){
35. Time tt;
36. tt.Hour = this->Hour +t.Hour;
37. tt.Minute = this->Minute + t.Minute;
38. tt.Second = this->Second + t.Second;
39. if(tt.Second>=60){
40. tt.Second = tt.Second - 60;
41. tt.Minute ++;
42. }
43. if(tt.Minute>=60){
44. tt.Minute =tt.Minute -60;
45. tt.Hour++;
46. }
47. if(tt.Hour>=24){
48. tt.Hour = tt.Hour -24;
49. }
50. return tt;
51.}
main2.cpp
1.#include "DateTimeFunction.cpp"
2.#include<iostream>
3.
4.using namespace std;
5.
6.int main(){
7. Calender cal;
8. Date date;
9. Time time;
10. date.init(2020,4,5);
11. time.init(10,27,56);
12. cal.date = date;
13. cal.time = time;
14. cal.show();
15. return 0;
16.}
運行結果: