C++初阶小项目——日期类的实现

前言:在完成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为负数 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值