日期类的实现
#include<iostream>
#include<assert.h>
#include<vld.h>
#include<time.h>
#include<windows.h>
using namespace std;
class Date
{
friend ostream& operator<<(ostream& out, const Date& dt);
public:
Date() : m_year(0), m_month(1), m_day(1)
{}
Date(int year, int month, int day) :m_year(year), m_month(month), m_day(day)
{}
Date(const Date& d)
{
m_year = d.m_year;
m_month = d.m_month;
m_day = d.m_day;
}
Date& operator=(const Date& d)
{
if (this != &d)
{
m_year = d.m_year;
m_month = d.m_month;
m_day = d.m_day;
}
return *this;
}
~Date()
{}
public:
bool operator>(const Date& d)
{
return (m_year > d.m_year ||
(m_year == d.m_year && m_month > d.m_month) ||
(m_year == d.m_year && m_month == d.m_month && m_day > d.m_day));
}
bool operator <= (const Date& d)
{
return !(*this > d);
}
bool operator < (const Date& d)
{
return (m_year < d.m_year ||
(m_year == d.m_year && m_month < d.m_month) ||
(m_year == d.m_year && m_month == d.m_month && m_day < d.m_day));
}
bool operator >= (const Date& d)
{
return !(*this < d);
}
bool operator==(const Date& d)
{
return (m_day == d.m_day && m_month == d.m_month && m_year == d.m_year);
}
bool operator != (const Date& d)
{
return !(*this == d);
}
public:
int GetDayByYM(int year, int month)
{
int days[] = { 29, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month == 2)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
month = 0;
}
return days[month];
}
Date operator+(int n)
{
Date tmp = *this;
int days = GetDayByYM(tmp.m_year, tmp.m_month);
int day = n + tmp.m_day;
while (day > days)
{
tmp.m_month++;
if (tmp.m_month > 12)
{
tmp.m_year++;
tmp.m_month = 1;
}
n -= days;
days = GetDayByYM(tmp.m_year, tmp.m_month);
day = n + tmp.m_day;
}
tmp.m_day += n;
return tmp;
}public:
Date& operator++()
{
*this = *this + 1;
return *this;
}
Date operator++(int)
{
Date tmp = *this;
++* this;
return tmp;
}
public:
int operator-(const Date& d);
public:
int GetWeek(int year, int month, int day);
public:
void PrintMonthCalc(int year, int month);
public:
void GetCurDateTime()
{
time_t te;
while (1)
{
time(&te);
struct tm* ptm = localtime(&te);
m_year = ptm->tm_year + 1900;
m_month = ptm->tm_mon + 1;
m_day = ptm->tm_mday;
printf("%d年%d月%d日 %d:%d:%d", m_year, m_month, m_day, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
Sleep(1000);
system("cls");
}
}
private:
int m_year;
int m_month;
int m_day;
};
ostream& operator<<(ostream& out, const Date& dt)
{
out << dt.m_year << "年" << dt.m_month << "月" << dt.m_day << "日";
return out;
}
void main()
{
Date dt1(2022, 5, 22);
cout << dt1 << endl;
dt1++;
cout << dt1 << endl;
}