【C++】日期类的实现

news2025/8/10 9:15:31

​🌠 作者:@阿亮joy.
🎆专栏:《吃透西嘎嘎》
🎇 座右铭:每个优秀的人都有一段沉默的时光,那段时光是付出了很多努力却得不到结果的日子,我们把它叫做扎根
在这里插入图片描述

目录

    • 👉前言👈
    • 👉Date.h👈
    • 👉Date.cpp👈
    • 👉Test.cpp👈
    • 👉总结👈

👉前言👈

在前三篇的类和对象的博客中,本人已经讲解了类和对象的全部知识点。这些知识点都是通过我们比较熟悉的日期类Date、栈Stack和队列MyQueue来讲解的,那么本篇文章就将日期类的实现总结一下。

👉Date.h👈

头文件Date.h里主要放着头文件的包含、类型的声明、函数的声明。日期类主要需要实现的函数有构造函数(注:析构函数和拷贝构造函数不需要自己写,编译器默认生成的就够用了)、运算符重载、计算日期是一年中的第几天以及将一年中的第几天转换成日期。

主要:在类中定义的成员函数会被当做内联函数处理,我们可以将被频繁调用的小函数在类中定义,不经常被调用的函数在类外定义。因为流插入<<和流提取>>的重载在类中定义,可读性不高,不符合使用习惯,所以我们利用友元将这两个函数重载在类外定义。

#pragma once
#include <iostream>
using namespace std;

class Date
{
public:
	// 友元声明(类的任意位置)
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);

	int GetMonthDay(int year, int month)
	{
		static int monthDayArray[13] = { 0,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;
		}
		else
		{
			return monthDayArray[month];
		}
	}

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

		// 检查日期是否合法
		if (!(year >= 1
			&& (month >= 1 && month <= 12)
			&& (day >= 1 && day <= GetMonthDay(year, month))))
		{
			cout << "非法日期" << endl;
		}
	}

	void Print() const
	{
		cout << _year << '/' << _month << '/' << _day << endl;
	}

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

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

	// d1 + 100
	Date operator+(int day) const;

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

	// d1 - 100
	Date operator-(int day) const;

	// 前置
	Date& operator++();

	// 后置
	Date operator++(int);

	// 前置
	Date& operator--();

	// 后置
	Date operator--(int);

	// d1 - d2
	int operator-(const Date& d) const;

	Date* operator&()
	{
		return this;
		// 要求这个类的对象不让取地址
		//return nullptr;
	}

	const Date* operator&() const
	{
		return this;
		//return nullptr; 
	}

	// 计算日期是一年中的第几天
	int DayOfYear() const;

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

// operator<<(cout, d1) cout<<d1
inline ostream& operator<<(ostream& out, const Date& d)
{
	out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
	return out;
}
// cin >> d1  operator(cin, d1)
inline istream& operator>>(istream& in, Date& d)
{
	in >> d._year >> d._month >> d._day;
	return in;
}

// 将一年中的第几天转换成日期
void DaysToDate();

👉Date.cpp👈

日期类需要实现的函数大多数是运算符重载,这些运算符重载在类和对象(中)这篇文章里讲过。如果还有不懂,可以点击跳转学习一下。运算符重载最重要的就是学会赋用已经写好的运算符重载,这样可以达到事半功倍的效果。

#include "Date.h"

bool Date::operator==(const Date& d) const
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

bool Date::operator>(const Date& d) const
{
	if (_year > d._year)
	{
		return true;
	}
	else if (_year == d._year && _month > d._month)
	{
		return true;
	}
	else if (_year == d._year && _month == d._month && _day > d._day)
	{
		return true;
	}
	
	return false;
}

bool Date::operator>=(const Date& d) const
{
	return *this > d || *this == d;
}

bool Date::operator<=(const Date& d) const
{
	return !(*this > d);
}

bool Date::operator<(const Date& d) const
{
	return !(*this >= d);
}

bool Date::operator!=(const Date& d) const
{
	return !(*this == d);
}

Date& Date::operator+=(int day)
{
	if (day < 0)
	{
		return *this -= -day;
	}

	_day += day;
	while (_day > GetMonthDay(_year, _month))
	{
		_day -= GetMonthDay(_year, _month);
		++_month;

		if (_month == 13)
		{
			++_year;
			_month = 1;
		}
	}

	return *this;
}

Date Date::operator+(int day) const
{
	Date ret(*this);
	ret += day;
	return ret;
}

Date& Date::operator-=(int day)
{
	if (day < 0)
	{
		return *this += -day;
	}

	_day -= day;
	while (_day <= 0)
	{
		--_month;
		if (_month == 0)
		{
			--_year;
			_month = 12;
		}

		_day += GetMonthDay(_year, _month);
	}

	return *this;
}

Date Date::operator-(int day) const
{
	Date ret(*this);
	ret -= day;
	return ret;
}

// 前置
Date& Date::operator++()
{
	*this += 1;
	return *this;
}

// 后置 -- 多一个int参数主要是为了根前置区分
// 构成函数重载
Date Date::operator++(int)
{
	Date tmp(*this);
	*this += 1;
	return tmp;
}

// 前置
Date& Date::operator--()
{
	*this -= 1;
	return *this;
}

// 后置
Date Date::operator--(int)
{
	Date tmp(*this);
	*this -= 1;
	return tmp;
}

// 日期差值 d1 - d2
int Date::operator-(const Date& d) const
{
	Date max = *this;
	Date min = d;
	int flag = 1;

	if (*this < d)
	{
		max = d;
		min = *this;
		flag = -1;
	}

	int n = 0;
	while (min != max)
	{
		++n;
		++min;
	}

	return n * flag;
}

int Date::DayOfYear() const
{
	static int Day[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };

	int n = Day[_month - 1] + _day;

	if (_month > 2 && ((_year % 4 == 0 && _year % 100 != 0) || (_year % 400 == 0)))
		++n;

	return n;
}

void DaysToDate()
{
	int year = 0;
	int days = 0;
	cin >> year >> days;

	static int Day[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	if (((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
		&& (days > 60))
	{
		--days;
	}

	int month = 1;
	while (days > Day[month])
	{
		days -= Day[month];
		month++;
	}

	printf("%04d-%02d-%02d\n", year, month, days);
}

计算日期是一年中的第几天

  • 定义一个数组,数组里存储的是到这个月的月底是该年的第几天
  • 计算日期是一年中的第几天n = Day[_month - 1] + _day
  • 如果月份month大于 2 且年份year为闰年,则n++
int Date::DayOfYear() const
{
	static int Day[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };

	int n = Day[_month - 1] + _day;

	if (_month > 2 && ((_year % 4 == 0 && _year % 100 != 0) || (_year % 400 == 0)))
		++n;

	return n;
}

将一年中的第几天转换成日期

  • 定义一个数组,数组中存储着平年每个月份的天数
  • 如果年份year为闰年且天数days大于 60,则--days
  • 定义月份month = 1,当days > Day[month]时,进入 while 循环,days -= Day[month] month++;当 while 循环结束时,就能求出monthdays
  • 注:1 <= days <= 366
void DaysToDate()
{
	int year = 0;
	int days = 0;
	cin >> year >> days;

	static int Day[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	if (((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
		&& (days > 60))
	{
		--days;
	}

	int month = 1;
	while (days > Day[month])
	{
		days -= Day[month];
		month++;
	}

	printf("%04d-%02d-%02d\n", year, month, days);
}

👉Test.cpp👈

Test.cpp源文件主要负责测试函数接口实现得是否正确。验证函数接口都正确后,就可以写过菜单来和用户交互了。不过,本人不太推荐写菜单,所以我就没有写菜单了。如果大家有需求的话,也可以自己写一写菜单。

#include "Date.h"

void TestDate1()
{
	Date d1(2022, 11, 14);
	Date d2(2022, 11, 15);
	
	cout << (d1 == d2) << endl;
	cout << (d1 > d2) << endl;
	cout << (d1 >= d2) << endl;
	cout << (d1 <= d2) << endl;
	cout << (d1 < d2) << endl;
	cout << (d1 != d2) << endl;

	cout << (d1 += 100);
	cout << (d2 -= 100);

	cout << d1.DayOfYear() << endl;

	DaysToDate();
}

int main()
{
	TestDate1();
	return 0;
}

在这里插入图片描述

在这里插入图片描述
看完本篇博客,大家可以做一下下面几道 OJ 题来巩固自己所学到的知识哦。

  • 计算日期到天数的转换 (OJ链接)
  • 日期差值(OJ链接)
  • 打印日期(OJ链接)
  • 累加天数(OJ链接)

👉总结👈

本篇博客主要是对前三篇类和对象写的日期类的小总结,如果大家觉得有收获的话,可以点个三连支持一下!谢谢大家啦!💖💝❣️

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/15498.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MySQL8.0优化 - 事务的隔离级别

文章目录学习资料事务的隔离级别脏读、不可重复读、幻读脏读&#xff08;Dirty Read&#xff09;不可重复读&#xff08;Non-Repeatable Read&#xff09;幻读&#xff08;Phantom&#xff09;SQL中的四种隔离级别读未提交&#xff08;READ UNCOMMITTED&#xff09;读已提交&am…

北京化工大学数据结构2022/11/17作业 题解

(7条消息) 食用前须知&#xff08;阅读并同意后在食用其他部分&#xff09;_lxrrrrrrrr的博客-CSDN博客 看完进来哈 目录 问题 A: 邻接矩阵存储的图&#xff0c;节点的出度和入度计算(附加代码模式) 问题 B: 算法7-12&#xff1a;有向无环图的拓扑排序 问题 C: 有向图是否存…

剪枝算法:通过网络瘦身学习高效卷积网络

摘要 原文链接&#xff1a;https://arxiv.org/abs/1708.06519 深度卷积神经网络(CNNs)在现实世界中的应用很大程度上受到其高计算成本的阻碍。在本文中&#xff0c;我们提出了一种新的cnn学习方案&#xff0c;以同时减小模型的尺寸;2)减少运行时内存占用;3)在不影响精度的前…

[附源码]java毕业设计企业职工福利发放管理系统

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…

WPF TreeView数据回填

这一期简单的说一下这个TreeView的数据回填&#xff0c; 上图是查询类型数据 上图是服务端的数据传递&#xff0c; 从数据库对应的查询出的数据传到服务端然后再传到客户端 上图就是在客户端后台启用刷新中的代码&#xff0c; DefaultView 获取自定义的视图 ItemsSource 获取…

如何在两个相关泛型类之间创建类似子类型的关系

本文正在参加「金石计划 . 瓜分6万现金大奖」 哈喽大家好&#xff0c;我是阿Q&#xff01; 事情是这个样子的...... 对话中的截图如下&#xff1a; 看了阿Q的解释&#xff0c;你是否也和“马小跳”一样存在疑问呢&#xff1f;请往&#x1f447;看 我们都知道在java中&#x…

领英高效开发客户方法(建议收藏)

领英高效开发客户 有效使用linkedIn领英&#xff0c;充分利用其人脉来为我们外贸人开发客户服务&#xff0c;我们也能获得外贸业-务更多更好机遇&#xff0c;扩大自己的外贸人脉圈。 在这里和大家分享一下&#xff0c;如何利用好领英linkedIn&#xff0c;轻松免-费地开发国外客…

深度学习入门(四十二)计算机视觉——目标检测和边界框

深度学习入门&#xff08;四十二&#xff09;计算机视觉——目标检测和边界框前言计算机视觉——目标检测和边界框课件图片分类和目标检测边缘框目标检测数据集总结教材1 边界框2 小结前言 核心内容来自博客链接1博客连接2希望大家多多支持作者 本文记录用&#xff0c;防止遗忘…

m基于MATLAB数字调制解调仿真,包括ASK,FSK,DPSK及MDPSK,对比误码率

目录 1.算法概述 2.仿真效果预览 3.MATLAB部分代码预览 4.完整MATLAB程序 1.算法概述 振幅键控&#xff08;也称幅移键控&#xff09;&#xff0c;记做ASK,或称其为开关键控&#xff08;通断键控&#xff09;&#xff0c;记做OOK 。二进制数字振幅键控通常记做2ASK。 对于振…

Spring Cloud(十一):Spring Cloud Security Oauth2

OAuth2 登录历程 basic 用户名&#xff1a;密码session cookietokenjwt 登录流程分析&#xff1a; https://www.processon.com/view/link/60a32e7a079129157118740f 微信开发平台文档&#xff1a; https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Logi…

(2)paddle---简单线性回归和波士顿房价预测

1、参考地址 &#xff08;1&#xff09;blibli网站地址 251-03_PaddlePaddle求解线性模型_dec_哔哩哔哩_bilibili &#xff08;2&#xff09;波士顿数据集介绍参考了 机器学习:波士顿房价数据集_mjiansun的博客-CSDN博客 2、简单线性回归 &#xff08;1&#xff09;测试一…

上海亚商投顾:沪指失守3100点 教育板块逆势大涨

上海亚商投顾前言&#xff1a;无惧大盘大跌&#xff0c;解密龙虎榜资金&#xff0c;跟踪一线游资和机构资金动向&#xff0c;识别短期热点和强势个股。 市场情绪大小指数今日走势分化&#xff0c;沪指震荡调整&#xff0c;尾盘再度失守3100点&#xff0c;创业板指盘中涨超1%&am…

定制activemq_RPM包,注册系统服务并开机自启

rpmbuild命令用于创建软件的二进制包和源代码包。 1.准备环境 系统&#xff1a;Centos7 安装所需编译环境&#xff1a; # yum install epel-release -y # yum install rpmdevtools rpm-build gcc make tcl jemalloc -y 2.提前编译安装redis&#xff0c;此处以activemq-5…

nodejs学习week01

说明&#xff1a;学习nodejs之气那应该掌握html&#xff0c;css&#xff0c;JavaScript等前端基础技术 目录 一、什么是nodejs 二、nodejs的内部模块 1.fs文件系统模块 2.path路径模块 3.http服务器模块 三、module.exports对象 四、时间格式化 1.使用JavaScript的方…

Python自动化运维之一(Python入门)

Python简介 python是吉多范罗苏姆发明的一种面向对象的脚本语言&#xff0c;可能有些人不知道面向对象和脚本具体是什么意思&#xff0c;但是对于一个初学者来说&#xff0c;现在并不需要明白。大家都知道&#xff0c;当下全栈工程师的概念很火&#xff0c;而Python是一种全栈的…

docker-compose模板文件、命令的使用

docker-compose官网 一、docker-compose的命令 1、up(启动) 格式为 docker-compose up [options] [SERVICE…] 该命令十分强大&#xff0c;它将尝试自动完成包括构建镜像&#xff0c;&#xff08;重新&#xff09;创建服务&#xff0c;启动服务&#xff0c;并关联服务相关容器…

FAQ是什么?该如何编辑FAQ?

“FAQ”这个关键词可能很多人都见过&#xff0c;但是如果不是行业内的人&#xff0c;大概还不知道它的含义&#xff0c;所以本文将介绍 FAQ和 FAQ文档的编写。 “FAQ”是中文意思&#xff0c;意思是“常见问题解答”或“帮助中心”。研究显示&#xff0c;客户服务支持每天要花…

第四章. Pandas进阶—数据分组统计

第四章. Pandas进阶 4.3 数据分组统计 1.分组统计函数(groupby函数) 1).功能&#xff1a; 根据给定的条件将数据拆分成组每个组否可以独立应用函数&#xff08;sum&#xff0c;mean&#xff0c;min&#xff09;将结果合并到一个数据结构中 2).语法&#xff1a; DataFrame.gro…

5G无线技术基础自学系列 | 物理上行共享信道

素材来源&#xff1a;《5G无线网络优化实践》 一边学习一边整理内容&#xff0c;并与大家分享&#xff0c;侵权即删&#xff0c;谢谢支持&#xff01; 附上汇总贴&#xff1a;5G无线技术基础自学系列 | 汇总_COCOgsta的博客-CSDN博客 NR PUSCH支持两种波形&#xff08;参阅TS…

Python入门自学进阶-Web框架——26、DjangoAdmin项目应用-数据记录操作

对于每个表显示的数据&#xff0c;点击其中一条&#xff0c;进入这条数据的修改页面&#xff0c;显示此条数据的具体内容&#xff0c;并提供修改、删除等功能。主要是ModelForm的应用。 一、记录数据修改 首先是路由项的添加&#xff0c;点击一条记录后&#xff0c;进入相应的…