面试题(日期类)C++版
2017-11-17 17:27
309 查看
写在前面:
当我们的面试官问你,你能不能写一个日期类?
这时,当你看过这篇博客,并记得实现的函数,那还有啥说的,你已经比人家高一个起点了,
日期类考点集中,难度不大(当然前提是你自己研究过),
话不多说,展示代码,我会在代码中一些重要的地方做注释
#include<iostream> using namespace std; 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)//构造函数 { if (! (year >= 1990 && (month > 0 && month<13) && day>0 && GetMonthdays(year, month)) )//日期合法性检测(不合法是让日期初始化为1990,1,1) { _year = 1990; _month = 1; _day = 1; } } //这里为什么没有想其他类一样给出拷贝构造函数,赋值运算符重载函数,以及析构函数呢? //因为我们这个类中不涉及到堆空间等资源的运用,给我们默认合成的上述函数可以用,故而,不需要给出。 //以下中出现的Date1,Date2,Date3为Date的3个对象 Date operator+(int days)//加号运算符重载(Date3=Date2+Date1) { if (days<0) return *this - (0 - days); Date temp(*this); temp._day += days; int daysInMOnth = 0; //函数原型:int GetMonthdays(int year, int month)用于获取当前年,该月中的总天数,返回值带回 if (temp._day > (daysInMOnth = GetMonthdays(temp._year, temp._month))) { temp._day -= daysInMOnth; temp._month++; if (temp._month > 12) { temp._year++; temp._month = 1< b88a /span>; } } return temp; } Date operator-(int days) { if (days>0)//当发现传过来的天数为正值,转去调用上面的函数 return *this + (0 - days); Date temp(*this); temp._day -= days; if (temp._day <= 0) { temp._month--; if (temp._month == 0) { temp._year--; temp._month = 12; } temp._day += GetMonthdays(temp._year, temp._month); } return temp; } int operator-(const Date d) { Date maxDate(*this); Date minDate(d); if (maxDate < minDate) { minDate = *this; maxDate = d; } int count = 0; while (minDate != maxDate) { count++; minDate++; } return count; } bool operator<(const Date d) { if (_year>d._year || _year == d._year&&_month > d._month || _year == d._year&&_month == d._month&&_day > d._day) return true; else return false; } Date& operator++()//前置++运算符重载 { *this = *this + 1; return *this; } Date operator++(int)//后置++运算符重载 { /* Date temp(*this); _day += 1; if (_day > GetMonthdays(_year, _month)) { _month += 1; if (_month > 12) _year += 1; _day = 1; } return temp; */ Date temp(*this); *this = *this + 1; return temp; } Date& operator--()//前置--运算符重载 { *this = *this - 1; return *this; } Date operator--(int)//后置--运算符重载 { Date temp(*this); *this = *this - 1; return temp; } bool operator==(const Date& d) { return _year == d._year&&_month == d._month&&_day == d._day; } bool operator!=(const Date& d) { /* if (_year == d._year&&_month == d._month&&_day ==d._day) return false; else return true; */ return !((*this) == d); } friend ostream& operator<<(ostream& _cout, const Date& d)//输出运算符“<<”的重载 { _cout << d._year << "-" << d._month << "-" << d._day; return _cout; } int GetMonthdays(int year, int month) { int Month[] = { 0, 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) return Month[month] + 1; } return Month[month]; } }; int main(void) { Date d1(2017, 11, 16); cout << d1 << endl; Date d2; d2 = d1 + 100; cout << d2 << endl; d2 = d1 - 500; cout << d2 << endl; }