c++實現一個日期類

//日期類


class Date {
public:
	void Display() {
		cout << _year << "-" << _month << "-" << _day << endl;
	}
	int GetMonthDay(int year, int month)const {
		static int arr[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 arr[month];
	}
	Date(int year = 1900, int month = 1, int day = 1) {
		if (year >= 1900 
			&& month > 0 && month <13 
			&& day >0 && day <= GetMonthDay(year, month)) {
			_year = year;
			_month = month;
			_day = day;
		}
		else {
			cout << "非法日期" << endl;
		}
	}
	Date(const Date& d) {
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	Date& operator=(const Date& d) {
		if (this != &d) {
			_year = d._year;
			_month = d._month;
			_day = d._day;
		}
		return *this;
	}
	Date operator+=(int days) {
		if (days < 0) {
			return *this -= (-days);
		}
		_day += days;
		while (_day > GetMonthDay(_year,_month)) {
			_day -= GetMonthDay(_year, _month);
			_month++;
			if (_month > 12) {
				_month = 1;
				_year++;
			}
		}
		return *this;
	}
	Date operator-=(int days) {
		if (days < 0) {
			return *this += (-days);
		}
		_day -= days;
		while (_day <= 0) {
			_month--;
			if (_month == 0) {
				_year--;
				_month = 12;
			}
			_day += GetMonthDay(_year, _month);
		}
		return *this;
	}
	Date operator+(int days)const {
		Date ret = (*this);
		ret += days;
		return ret;
	}
	Date operator-(int days)const {
		Date ret = (*this);
		ret -= days;
		return ret;
	}
	int operator-(const Date& d)const {
		Date maxDate(*this);
		Date minDate(d);
		int falg = 1;
		if (*this < d) {
			maxDate = d;
			minDate = *this;
			falg = -1;
		}
		int days = 0;
		while (minDate != maxDate) {
			minDate += 1;
			days++;
		}
		return falg * days;
	}
	Date& operator++() {
		(*this) += 1;
		return *this;
	}
	Date operator++(int) {//後置++
		Date ret = *this;
		*this += 1;
		return ret;
	}
	Date& operator--() {
		*this -= 1;
		return *this;
	}
	Date operator--(int) {
		Date ret(*this);
		*this -= 1;
		return ret;
	}
	bool operator>(const Date& d)const {
		if (_year > d._year) {
			return true;
		}
		else if(_year == d._year){
			if (_month > d._month) {
				return true;
			}
			else if(_month == d._month) {
				if (_day > d._day) {
					return true;
				}
			}
		}
		return false;
	}
	bool operator>=(const Date& d)const {
		return *this > d || *this == d;
	}
	bool operator<(const Date& d)const {
		return !(*this >= d);
	}
	bool operator<=(const Date& d)const {
		return !(*this > d);
	}
	bool operator==(const Date& d)const {
		if (_year == d._year && _month == d._month && _day == d._day) {
			return true;
		}
		return false;
	}
	bool operator!=(const Date& d)const  {
		return !(*this == d);
	}
private:
	int _year;
	int _month;
	int _day;
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章