C++小练习--实现一个完整的日期类

创建一个Date.h文件用来声明Date日期类的类,以便管理。

class Date
{
public:
	//构造函数
	Date(int year = 1, int month = 1, int day = 1);
	void Print();


	bool operator>(const Date& d);
	bool operator<(const Date& d);
	bool operator>=(const Date& d);
	bool operator<=(const Date& d);
	bool operator==(const Date& d);
	bool operator!=(const Date& d);

	Date& operator+=(int day);//d1+=100
	Date operator+(int day);//d1+100

	Date& operator-=(int day);//d1-=100
	Date operator-(int day);//d1-100
private:
	int _year;
	int _month;
	int _day;
};

这里是我们要实现的成员函数。

创建一个Date.cpp源文件,包头文件

#include "Date.h"

构造函数

众所周知缺省函数在头文件声明的话,就不能在源文件中声明,二者只能声明一个,且只能在头文件.h中使用缺省参数。

Date::Date(int year,int month,int day)
{
	_year = year;
	_month = month;
	_day = day;

}

并写出打印函数

void Date::Print()
{
	cout << _year << "-" << _month << "-" << _day << endl;
}

测试一下

void DateTest1()
{
	Date d1;
	Date d2(2022, 1, 16);

	d1.Print();
	d2.Print();

	Date d3(2022, 13, 15);
	d2.Print();

	Date d4(2022, 2, 29);
	d3.Print();

	Date d5(2020, 2, 29);
	d4.Print();

	Date d6(2000, 2, 29);
	d6.Print();
}

发现一些非法日期,比如上述的月份大于12,非闰月天数为29,这种非法日期。,所以需要在构造函数初始化的时候判断日期合法性。

【判断方法】

如果year大于0,month大于0,小于13,day大于0,小于该月的天数,及为合法,那么想要获得该月的天数,我们写一个函数获取该月的天数。

写一个数组,传入月数,即可获得该月的天数,那么2月还需要判断一下,是否是闰年。

润年

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值