在完成日期类时,涉及到对应月份天数的限制,先构造出下面的函数,用以判断当月天数。
int Date::GetMonthDay(int year, int month)
{static int daysArray[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };int days = daysArray[month];if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))){days = 29;}return days;
}
Date.h文件
#pragma once
#include
using namespace std;
class Date
{
public:int GetMonthDay(int year, int month);void Print();Date(int year &#61; 1900, int month &#61; 1, int day &#61; 1);Date(const Date& d);Date& operator&#61;(const Date& d);~Date();Date& operator&#43;&#61;(int day);Date operator&#43;(int day);Date& operator-&#61;(int day);Date operator-(int day);Date& operator&#43;&#43;();Date operator&#43;&#43;(int);bool operator>(const Date& d);bool operator&#61;&#61;(const Date& d);inline bool operator >&#61; (const Date& d);bool operator < (const Date& d);bool operator <&#61; (const Date& d);bool operator !&#61; (const Date& d);int operator-(const Date& d);
private:int _year;int _month;int _day;
};
Date.cpp文件
#include"Date.h"Date::Date(const Date& d)
{_year &#61; d._year;_month &#61; d._month;_day &#61; d._day;
}Date& Date::operator&#61;(const Date& d){if (this !&#61; &d){_year &#61; d._year;_month &#61; d._month;_day &#61; d._day;}return *this;}Date:: ~Date(){cout << "~Date()" << endl;}
void Date::Print()
{cout << _year << "-" << _month << "-" << _day << endl;
}
int Date::GetMonthDay(int year, int month)
{static int daysArray[13] &#61; { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };int days &#61; daysArray[month];if (month &#61;&#61; 2 && ((year % 4 &#61;&#61; 0 && year % 100 !&#61; 0) || (year % 400 &#61;&#61; 0))){days &#61; 29;}return days;
}
Date::Date(int year, int month, int day)
{_year &#61; year;_month &#61; month;_day &#61; day;