1. 程式人生 > >C++實現一個日期

C++實現一個日期

#include<iostream>
using namespace std;
class Date
{
public:
 Date(int year = 1900, int month = 1, int day = 1)//類的初始化
  :_year(year)
  , _month(month)
  , _day(day)
 {
  if (!IsInvalidDate())
  {
   _year = 1900;
   _month = 1;
   _day = 1;
  }
 }
 Date operator+(int days)//實現日期的+操作

 {
  if (days<
0) return *this - (0 - days); Date temp(*this); temp._day += days; int DaysOfMonth = 0; while (temp._day >(DaysOfMonth = _CetDaysOfMonth(temp._year, temp._month))) { temp._day -= DaysOfMonth; ++temp._month; if (temp._month > 12) { temp._year += 1; temp._month = 1
; } } return temp; } Date operator-(int days)//實現日期的-操作 { if (days < 0) return *this + (0 - days); Date temp(*this); temp._day -= days; while(temp._day <= 0) { temp._month -= 1; if (0 == temp._month) { temp._year -= 1; temp._month = 12; } temp._day +=
_CetDaysOfMonth(temp._year, temp._month); } return temp; } Date& operator++()//前置++ { *this = *this + 1; return *this; } Date operator++(int)//後置++ { Date temp(*this); ++(*this); return temp; } Date& operator--()//前置-- { *this = *this -1; return *this; } Date operator--(int)//後置-- { Date temp(*this); --(*this); return temp; } //2018 11 4 //2019 1 1 int operator-(const Date& d) { Date MinDate(*this); Date MaxDate(d); if (*this > d) { MinDate = d; MaxDate = *this; } int count = 0; while (MinDate != MaxDate) { ++count; ++MinDate; } return count; } bool operator==(const Date & d)const { return _year == d._year && _month == d._month && _day == d._day; } bool operator>(const Date& d)const { if ((_year > d._year) || (_year == d._year && _month > d._month) || (_year == d._year && _month == d._month && _day > d._day)) { return true; } return false; } bool operator!=(const Date& d)const { return !(*this == d); } private: bool IsInvalidDate()//判斷一個日期是否合法 { if (((_year >0) && (_month >0 && _month<13) && (_day > 0 && _day <= _CetDaysOfMonth(_year, _month)))) { return true; } return false; } int _CetDaysOfMonth(int year, int month) { int days[] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; if (2 == month && _IsLeapYear(year)) days[month] += 1; return days[month]; } bool _IsLeapYear(int year) { if ((0 == year % 4 && 0 != year % 100) || (0 == year % 400)) { return true; } return false; } friend ostream& operator<<(ostream& _cout, const Date& d) { _cout << d._year << "-" << d._month << "-" << d._day; return _cout; } friend istream& operator>>(istream& _cin, Date& d) { _cin >> d._year >> d._month >> d._day; if (!d.IsInvalidDate()) cout << "輸入的日期非法:" << d << endl; return _cin; } private: int _year; int _month; int _day; }; int main() { Date d1(2018, 11, 4); cout << d1-999<< endl; Date d2(2019, 1, 1); cout << d1 - d2 << endl; cout << d2 - d1 << endl; return 0; }