前言:在完成c++入门基础及类和对象初步了解,旨在通过此项目完成类和对象相关操作的实践
一,完成准备工作
与之前类似,建立Date.h Date.cpp Test.cpp三个文件
Date.h
完成类及类函数的声明
Date.cpp
完成具体函数的实现
Test.cpp
测试程序可执行性
二, 具体函数的实现
1,构造函数Date(int year = 1900, int month = 1, int day = 1);
Date::Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
可以检查日期准确性
if (!CheckDate())
{
cout << "⽇期⾮法" << endl;
}
总代码
Date::Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
if (!CheckDate())
{
cout << "⽇期⾮法" << endl;
}
}
2,void Print();
void Date::Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
3,GetMonthDay(int year, int month);
//默认为内联函数incline
//频繁调用的简短内敛函数不用建立栈帧
int GetMonthDay(int year, int month)
{
static int monthDayArray[13] = { -1, 31, 28, 31, 30, 31, 30 ,31, 31, 30, 31, 30, 31 };
//判断闰年
//能被4整除,但不能被100整除
//能被400整除
if (month == 2 && (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
{
return 29;
}
return monthDayArray[month];
}
assert(month > 0 && month < 13);
int GetMonthDay(int year, int month)
{
assert(month > 0 && month < 13);
static int monthDayArray[13] = { -1, 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 monthDayArray[month];
}
注:该函数建立在类里面,因为类里面默认为内联函数incline,频繁调用的简短内敛函数不用建立栈帧
month == 2 在 (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
因为这样减少判断,极高效率
4,Date& operator+=(int day);
思路:先加上天数与当月总天数比较,比总天数大则减去 当月总天数 月份加一
单独考虑12月变为1月
Date& Date::operator+=(int day)
{
_day += day;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
++_month;
if (_month == 13)
{
_year++;
_month = 1;
}
}
return *this;
}
//第一种
Date d2 = d1 + 100;
//第二种
Date d3(d1 + 100);
注:需考虑day为负数