有关日期类的成员函数

来源:互联网 发布:php笑话模板wap 编辑:程序博客网 时间:2024/04/29 23:45

有关函数介绍:

1. 构造函数:存在默认参数,提供系统默认时间。

2.判断日期是否合法的函数:年是否大于默认年分,月是否在12内,天(根据闰年,平年判断)是否合法。

3.获得某月天数:·平闰年判断。

4.对日期的加减天数,需要借助2,3的函数判断某月天数和判断是否合法,以此进行借位或者进位。

5.日期见日期:通过小的天数向上加,统计天数。

实现代码如下:

#pragma once#include <iostream>using namespace std;#include <assert.h>class Date{private:int _year;int _month;int _day;public://构造函数,含有默认参数Date(int year = 1990, int month = 1, int day = 1): _year(year), _month(month), _day(day){assert(IsInvalid());}//判断日期是否合法bool IsInvalid(){if (_year >= 1990&& _month > 0 && _month < 13&& _day > 0 && _day <= GetMonthDays(_year, _month))return true;else return false;}//获得某月天数int GetMonthDays(int year, int month){static int MonthDays[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };if (month != 2)return MonthDays[month];elseif ((year % 4 == 0 && year % 100 != 0)|| year % 400 == 0)return 29;elsereturn 28;}//向日期加天数Date operator+(int day){if (day < 0){return *this - (-day);}Date tmp(*this);tmp._day += day;while (tmp.IsInvalid() == false){tmp._day -= GetMonthDays(tmp._year, tmp._month);if (tmp._month == 12){tmp._year++;tmp._month = 1;}else{tmp._month++;}}return tmp;}//向日期减天数Date operator-(int day){if (day < 0){return *this + (-day);}Date tmp(*this);tmp._day -= day;while (tmp.IsInvalid() == false){if (tmp._month == 1){tmp._year--;tmp._month = 12;}else{tmp._month--;}tmp._day += GetMonthDays(tmp._year, tmp._month);}return tmp;}//重载 -=inline Date& operator -=(int day){*this = *this - day;return *this;}//重载 前置++inline Date& operator++(){*this = *this + 1;return *this;}//重载后置++inline Date operator++(int){Date tmp(*this);tmp = *this + 1;return tmp;}//重载>bool operator > (const Date& d){if (_year > d._year|| (_year == d._year && (_month > d._month || (_month == d._month && _day > d._day)))){return true;}return false;}//重载 ==bool operator == (const Date& d){if (_year == d._year && _month == d._month && _day == d._day)return true;elsereturn false;}bool operator != (const Date& d){return !(*this == d);}//日期减去日期int operator-(const Date& d){Date tmp_this(*this);Date tmp_d(d);int flag = 1;int day = 0;if (tmp_this > d){swap(tmp_d._day, tmp_this._day);swap(tmp_d._month, tmp_this._month);swap(tmp_d._year, tmp_this._year);flag = -1;}while (tmp_this != tmp_d){++tmp_this;day++;}return day*flag;}void Dispaly(){cout << _year << "-" << _month << "-" << _day << endl;}};

0 0
原创粉丝点击