函数
四个基本函数
bool InvalidDate(int year, int month, int day)//判断日期是否非法,合法返回false,非法返回true
bool InvalidDate(int year, int month, int day)
{
if (year > 0 && \
month > 0 && month <= 12 && \
day > 0 && day <= GetMonthDay(year, month))
{
return false;
}
return true;
}
void Show() //打印日期
void Show()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
int GetMonthDay(int year, int month) //得到一个月的天数
int GetMonthDay(int year, int month)
{
int monthday[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if ((month == 2) && \
((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
{
return 29;
}
return monthday[month];
}
void SetDate(int year,int month,int day)//设置日期
void SetDate(int year,int month,int day)
{
if (!InvalidDate(year,month,day))
{
_year = year;
_month = month;
_day = day;
}
else
{
cout << "非法日期:" << year << "-" << month << "-" << day << endl;
}
}
四个默认函数
//构造函数(支持函数重载)
Date(int year = 1990, int month = 1, int day = 1)
{
assert(!InvalidDate(year, month, day));
_year = year;
_month = month;
_day = day;
cout << "Date(int year,int month,int day)" << endl;
}
Date(const Date& d)//拷贝构造
Date(const Date& d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
~Date()//析构函数:用来释放空间(一般动态申请的空间才会调用析构函数)
~Date()
{
}
Date& operator=(const Date& d)//赋值
Date& operator=(const Date& d)
{
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
运算符重载
两个日期比较大小
bool operator==(const Date& d)//operator==判断两个日期是否相等
bool operator==(const Date& d)
{
return (_year == d._year) && \
(_month == d._month) && \
(_day == d._day);
}
bool operator>(const Date& d)//d1>d2->operator(&d1,d2)
bool operator>(