C++ 日期计算器

本文详细介绍了如何在C++中实现一个Date类,包括构造函数、拷贝构造函数、析构函数,以及各种操作符重载如加减运算、比较运算等,以实现日期的计算功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

请添加图片描述

概要

本篇主要探究C++ 实现日期计算器

Date类的规划

class Date
{
   
public:
	int GetMonthDay(int year, int month);
	Date(int year = 2024 , int month = 2, int day = 6);
	Date(const Date& d);
	Date& operator=(const Date& d);
	~Date();
	Date& operator+=(int day);
	Date operator+(int day);
	Date operator-(int day);
	Date& operator-=(int day);
	Date& operator++();
	Date operator++(int);
	Date operator--(int);
	Date& operator--();
	bool operator>(const Date& d) const;
	bool operator==(const Date& d) const;
	bool operator>= (const Date& d) const;
	bool operator< (const Date& d) const;
	bool operator<= (const Date& d) const;
	bool operator!= (const Date& d) const;
	int operator-(const Date& d) const;
	void Print();

private:
	int _year;
	int _month;
	int _day;
};

Date类的实现

Date 构造函数

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

构造函数,他是在创建类的时候调用进行初始化操作,我们这里声明与定义分离,所以它的参数不需要填写缺省值,缺省值在声明的时候定义即可。

Date 拷贝构造函数

Date::Date(const Date& x)
	:_year(x._year)
	, _month(x._month)
	, _day(x._day)
{
    }

拷贝构造函数和构造函数作用相似,拷贝构造函数是将已有的类的对象拷贝给新创建的类的对象,如上所示。

~Date 析构函数

Date::~Date()
{
   
	_year = _month = _day = 0;
}

构析函数是在对象即将销毁前所调用的函数,常用来清理数据空间,这里我们的内存都在栈上申请的,所以影响不大。

GetMonthDay 求某年某月的天数

int Date::GetMonthDay(int year,int month)
{
   
	int a[13]={
   0,31,28,31,30,31,30,31,31,30,31,30<
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒋志昂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值