本文實作了一個簡單的 C++ 日期類,重點示範如何重載各種比較與算術運算符,讓日期物件能像內建型別一樣自然地進行加減與比較。
先看宣告 Date.h:
#define _CRT_SECURE_NO_WARNINGS 1
#ifndef __ONCEDATE__
#define __ONCEDATE__
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year = 1900, int mouth = 1, int day = 1);
bool operator == (const Date& d);
bool operator <(const Date& d);
bool operator <=(const Date& d);
bool operator >(const Date& d);
bool operator >=(const Date& d);
bool operator !=(const Date& d);
Date operator+ (int day);
Date operator+= (int day);
Date operator- (int day);
Date operator-= (int day);
Date operator++();
Date operator++(int);
Date operator--();
Date operator--(int);
void display();
int operator-(const Date& d);
private:
bool IsLeapYear(int year);
int GetMonthDay(int year, int month);
int _year;
int _mouth;
int _day;
};
#endif
定義部分如下,關鍵在於日期加減時要正確處理跨月與跨年的進位、借位:
void Date::display()
{
cout << _year << " " << _mouth << " " << _day << endl;
}
Date::Date(int year, int mouth, int day)
{
if ((year >= 0) && (mouth > 0 && mouth<13) &&
(day>0 && day <= GetMonthDay(year, mouth)))
{
_year = year; _mouth = mouth; _day = day;
}
else
{
cout << "日期錯誤,改為默認日期" << endl;
_year = 1900; _mouth = 1; _day = 1;
}
}
bool Date::operator == (const Date& d)
{
return this->_year == d._year && this->_mouth == d._mouth && this->_day == d._day;
}
Date Date::operator+ (int day)
{
Date DestDate(*this);
DestDate._day += day;
while (DestDate._day > GetMonthDay(DestDate._year, DestDate._mouth) || DestDate._day <= 0)
{
if (DestDate._day>0)
{
DestDate._day -= GetMonthDay(DestDate._year, DestDate._mouth);
if (DestDate._mouth == 12) { DestDate._mouth = 0; DestDate._year++; }
DestDate._mouth++;
}
else
{
DestDate._day += GetMonthDay(DestDate._year, DestDate._mouth);
if (DestDate._mouth == 1) { DestDate._mouth = 13; DestDate._year--; }
DestDate._mouth--;
}
}
return DestDate;
}
int Date::operator-(const Date& d)
{
Date high(d); Date low;
int count = 0; int flag = 1;
if (*this > d) { low = high; high = *this; }
else { flag = 0; low = *this; }
while (low != high) { low++; count++; }
if (!flag) count = -count;
return count;
}
bool Date::IsLeapYear(int year)
{
if (((year % 4 == 0) && (year % 100)) || (year % 400 == 0)) return true;
return false;
}
int Date::GetMonthDay(int year, int month)
{
int monthArray[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int day = monthArray[month];
if (month == 2 && IsLeapYear(year)) day += 1;
return day;
}
設計上的巧思在於:operator+ 用一個迴圈處理進借位,由於參數允許為負數,同一段邏輯也能兼顧減法;而閏年判斷(能被 4 整除但不能被 100 整除,或能被 400 整除)與每月天數則抽成私有函數,讓加減運算保持乾淨。如有不足,歡迎批評指正。