class myDate { public: myDate(const int y, const int m, const int d); int getYear(); int getMonth(); int getDay(); int getWeek(); //0\~6 蔡勒公式 bool setDate(const int y, const int m, const int d); bool isLeap(int y);//閏年 void output(); //輸出 year-month-day (week) private: int year; int month; int day; int week; };
const myDate operator+(myDate &d, const int n) //d+n天 { int Y, M, D; Y = d.getYear();//年 M = d.getMonth();//月 D = d.getDay() + n;//日 while (D > 28) { if (M == 1 || M == 3 || M == 5 || M == 7 || M == 8 || M == 10 || M == 12) { if (D > 31) { D = D - 31; M++; } else { break; } } else if (M == 4 || M == 6 || M == 9 || M == 11) { if (D > 30) { D = D - 30; M++; } else { break; } } else { if (d.isLeap(Y) == true) { if (D > 29) { D = D - 29; M++; } else { break; } } else { if (D > 28) { D = D - 28; M++; } else { break; } } } if (M > 12) { Y++; M = 1; } } return myDate(Y, M, D); }
const myDate operator-(myDate &d, const int n) //d-n天 { int Y, M, D; Y = d.getYear(); M = d.getMonth(); D = d.getDay() - n; while (D <= 0) { M--; if (M < 1) { Y--; M = 12; } if (M == 1 || M == 3 || M == 5 || M == 7 || M == 8 || M == 10 || M == 12) { D = D + 31; } else if (M == 4 || M == 6 || M == 9 || M == 11) { D = D + 30; } else { if (d.isLeap(Y) == true) { D = D + 29; } else { D = D + 28; } } } return myDate(Y, M, D); }
這部分就是對於opreator-的重載設定
第六部分:主功能解析-get函式設定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
myDate::myDate(const int y, const int m, const int d) { year = y; month = m; day = d; } int myDate::getYear() { return year; } int myDate::getMonth() { return month; } int myDate::getDay() { return day; }
int myDate::getWeek() { int w, c, y, m = month, d = day, x = year; if (m == 1 || m == 2) { m = m + 12; x = x - 1; c = x / 100; y = x - c * 100; w = (y + (y / 4) + (c / 4) - 2 * c + 2 * m + (3 * (m + 1) / 5) + d + 1); } else { c = x / 100; y = x - c * 100; w = (y + (y / 4) + (c / 4) - 2 * c + 2 * m + (3 * (m + 1) / 5) + d + 1); } if (w >= 0) { week = w % 7; return week; } else { week = (w % 7 + 7) % 7; return week; } }
bool myDate::setDate(const int y, const int m, const int d) { if (m < 1 || m > 12) { month = 1; day = 1; } else { month = m; if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) { if (d < 1 || d > 31) { month = 1; day = 1; } else { day = d; } } else if (m == 4 || m == 6 || m == 9 || m == 11) { if (d < 1 || d > 30) { month = 1; day = 1; } else { day = d; } } else if (isLeap(y) == true && m == 2) { if (d < 1 || d > 29) { month = 1; day = 1; } else { day = d; } } else { if (d < 1 || d > 28) { month = 1; day = 1; } else { day = d; } } } return true; }