我与C++的爱恋:日期计算器

news2024/9/28 11:09:02


外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

🔥个人主页guoguoqiang. 🔥专栏我与C++的爱恋

Alt

朋友们大家好啊,在我们学习了默认成员函数后,我们通过上述内容,来实现一个简易的日期计算器。


头文件的声明

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

#include <assert.h>
class Date {
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);
public:
	Date(int year = 1900, int month = 1, int day = 1);
	void Print() const;
	//直接定义类里面,它默认是inline
	//频繁调用
	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;
		}
		else {
			return monthDayArray[month];
		}
	}
	bool CheckDate();

	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;
	Date& operator+=(int day);
	Date operator+(int day)const;
	Date& operator-=(int day);
	Date operator-(int day)const;

	// 前置++
	Date& operator++();
	// 后置++
	Date operator++(int);
	// 后置--
	Date operator--(int);
	// 前置--
	Date& operator--();
	int operator-(const Date& d)const;
private:
	int _year;
	int _month;
	int _day;
};
// 重载
ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);

函数实现

获取某年某月的天数

class Date {
public:
	//直接定义类里面,它默认是inline
	//频繁调用
	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;
		}
		else {
			return monthDayArray[month];
		}
	}

为了按月份访问数组,所以我们设置大小为13,由于要多次访问,所以将这个数组变量设置在全局。
如果是2月并且是闰年则返回29,否则就返回当前月份的天数。

1.判断日期是否合法

bool Date::CheckDate() {
	if(_month<1||_month>12
		|| _day<1 || _day>GetMonthDay(_year, _month)) {
		return false;
	}
	else {
		return true;
	}
}

如果不合法则返回false,合法则返回true;

2.全缺省默认构造函数

Date ::Date(int year , int month , int day) {
	_year = year;
	_month = month;
	_day = day;
	if (!CheckDate())
	{
		cout << "日期非法" << endl;
	}
}

在头文件中缺省源文件中不需要。

3.拷贝构造函数

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

4.七个运算符重载

除了赋值运算符之外,我们只需要写一个等于和一个大于或者小于就可以简单的实现另外四个函数。

首先,==的重载

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) {
		if (_month < d._month) {
			return true;
		}
		else if (_month == d._month) {
			return _day < d._day;
		}
	}
	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=(const Date& d) {
	if (*this != d) {
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	return *this;
}

5.日期计算函数

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;
}

day超过该月的天数则++month,如果month==13则++year,再将month置为1月;

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

==Date& Date::operator+=(int day)==是会调用它本身然后返回修改后的对象

特点:

直接修改:它修改调用对象的状态,即增加的天数直接反映在原对象上
返回引用:返回调用它的对象的引用,允许链式操作
	Date d1(2024,  4, 15);
	d1 += 4;
	//这里d1变为2024 4 19

Date Date:: operator+(int day)const是创建一个临时变量,然后在这个临时变量上+=day,然后返回原变量+=day后的结果。
特点:
1.不直接修改,不会修改原对象,而是返回一个修改后的对象。
2.返回对象,是一个临时变量,返回原对象+=day后的结果。

	Date d1(2024,  4, 15);
	d1 += 4;
	Date d2=d1+4;//这里d2 变为2024 4 23   d1仍是2024 4 19
	//这里d1变为2024 4 19

如果我们要+嵌套到+=中呢?
在这里插入图片描述
对比我们能发现,两种加法都要创建一个新的变量,效果相同,但是加等,右边复用加的时候又创建对象,对比左边效率降低,所以用加复用加等效果更好

同理完成日期的减等和减

Date& Date:: operator-=(int day) {
	if (day < 0) {
		return *this += -day;
	}
	_day -= day;
	while (_day <= 0) {
		_day += GetMonthDay(_year, _month);
		_month--;
		if (_month == 0) {
			_year--;
			_month = 12;
		}
	}
	return *this;
}
Date Date:: operator-(int day) const {
	Date tmp = *this;
	tmp -= day;
	return tmp ;
}

6.前后置+±-;

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

7.两个日期相减

// 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)
	{
		++min;
		++n;
	}
	return n * flag;
}

先确定哪个日期小,再进行判别符号,再进行计算天数差通过!=直接判别(也可以使用<)不过小于的判别复杂,所以这里使用!=
++min(这里的++就是前置++);最后返回n*flag 如果flag=-1,表示第一个日期是小于第二个日期的,因此为负值。

8.重载输入输出

ostream& operator<<(ostream& out, const Date& d) {
	out << d._year << "年" << d._month << "月" << d._day<<"日"<<endl;
	return out;
}
istream& operator>>(istream& in, Date& d) {
	cout << "请依次输入年月日";
	in >> d._year >> d._month >> d._day;
	if (!d.CheckDate()) {
		cout << "日期非法" << endl;
	}
	return in;
}

operator<< 想重载为成员函数,可以,但是用起来不符合正常逻辑,不建议这样处理(因为Date*this占据一个参数位置d<<cout),建议重载为全局函数。

本篇内容到此结束,感谢大家观看!!!

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

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

相关文章

计算机服务器中了locked勒索病毒怎么办,locked勒索病毒解密工具流程步骤

随着网络技术的不断应用与发展&#xff0c;越来越多的企业离不开网络&#xff0c;网络大大提升了企业的办公效率水平&#xff0c;也为企业的带来快速发展&#xff0c;对于企业来说&#xff0c;网络数据安全成为了大家关心的主要话题。近日&#xff0c;云天数据恢复中心接到多家…

Spring - 2 ( 14000 字 Spring 入门级教程 )

一&#xff1a;Spring Web MVC⼊⻔ Spring Web MVC 是⼀个 Web 框架&#xff0c;简称之为: Spring MVC 要真正的理解什么是 Spring MVC&#xff1f;我们⾸先要搞清楚什么是 MVC&#xff1f; 1.1 MVC 定义 MVC 是 Model View Controller 的缩写&#xff0c;它是软件⼯程中的…

丰田是如何用精益理念改变制造业的?

丰田&#xff0c;这个全球知名的汽车制造商&#xff0c;不仅以其高质量的产品赢得了消费者的信赖&#xff0c;更以其独特的精益理念深刻改变了整个制造业的面貌。那么&#xff0c;丰田究竟是如何用精益理念引领制造业变革的呢&#xff1f;天行健精益管理培训公司解析如下&#…

了解BACnet的对象模型 (三)

文章目录 前言18个对象BACnet 对象的属性设备对象&#xff08;Device&#xff09;的属性输入输出值对象类型及其属性 在代码中的表达Device对象的属性模拟输入对象的属性 小结 前言 在楼宇自控网络中&#xff0c;各种设备之间要进行数据交换&#xff0c;为了能够实现设备的互操…

[C++][算法基础]求组合数(II)

给定 &#x1d45b; 组询问&#xff0c;每组询问给定两个整数 &#x1d44e;&#xff0c;&#x1d44f;&#xff0c;请你输出 的值。 输入格式 第一行包含整数 &#x1d45b;。 接下来 &#x1d45b; 行&#xff0c;每行包含一组 &#x1d44e; 和 &#x1d44f;。 输出格…

【Java框架】SpringMVC(二)——SpringMVC数据交互

目录 前后端数据交互RequestMapping注解基于RequestMapping注解设置接口的请求方式RequestMapping注解的常用属性一个方法配置多个接口method属性params属性headers属性consumes属性produces属性 SpringMVC中的参数传递默认单个简单参数默认多个简单参数默认参数中有基本数据类…

机器学习-11-基于多模态特征融合的图像文本检索

总结 本系列是机器学习课程的系列课程&#xff0c;主要介绍机器学习中图像文本检索技术。此技术把自然语言处理和图像处理进行了融合。 参考 2024年&#xff08;第12届&#xff09;“泰迪杯”数据挖掘挑战赛 图像特征提取&#xff08;VGG和Resnet特征提取卷积过程详解&…

Python 比较文本文件

1、问题背景 我们需要比较一个文本文件 F 与路径下多个其他文本文件之间的差异。我们已经编写了以下代码&#xff0c;但只能输出一个文件的比较结果。我们需要修改代码&#xff0c;以便比较所有文件并打印所有结果。 import difflib import fnmatch import osfilelist[] f op…

Linux 网络操作命令Telnet

Telnet 尽管 Telnet 已经逐渐被更安全的 SSH 协议所取代&#xff0c;但在某些特定场景下&#xff0c;如对旧系统的维护或教育目的&#xff0c;Telnet 仍然有其使用价值。本文将介绍如何在 Linux 系统中安装 Telnet 客户端&#xff0c;以及如何使用它进行远程登录。 用户使用 t…

基于SpringBoot+Vue的网上摄影工作室(含源码数据库+文档免费送)

项目演示视频&#xff1a; 基于SpringBootVue的网上摄影工作室&#xff08;含源码数据库文档免费送&#xff09; 基于SpringBootVue的网上摄影工作室&#xff08;含源码数据库文档免费送&#xff09; 开发系统:Windows10 架构模式:MVC/前后端分离 JDK版本: Java JDK1.8 开发工…

JEECG表格选中状态怎么去掉

官网代码&#xff08;在取消选中状态的时候不生效&#xff09; rowSelection() {return {onChange: (selectedRowKeys, selectedRows) > {console.log(selectedRowKeys: ${selectedRowKeys}, selectedRows: , selectedRows);},getCheckboxProps: record > ({props: {disa…

亚马逊、Lazada、速卖通怎么提高复购率?如何利用自养号测评实现销量飙升

对于跨境卖家来说&#xff0c;抓住客户是最重要的&#xff0c;很多卖家都把大部分心思放在如何吸引新客户上&#xff0c;忽视了已有客户的维护。其实相较于投广告、报秒杀活动吸引新客户&#xff0c;维护好已有客户&#xff0c;提升复购率的成本更低。当然&#xff0c;维护好客…

微软如何打造数字零售力航母系列科普02 --- 微软低代码应用平台加速企业创新 - 解放企业数字零售力

微软低代码应用平台推动企业创新- 解放企业数字零售力 微软在2023年GARTNER发布的魔力象限图中处于头部领先&#xff08;leader&#xff09;地位。 其LCAP产品是Microsoft Power Apps&#xff0c;扩展了AI Builder、Dataverse、Power Automate和Power Pages&#xff0c;这些都包…

Java 基础知识易错记录

Java 基础知识易错记录 ①运算符 ②continue和break ③成员变量 局部变量 ④switch case ⑤StringBuffer StringBuilder ⑥重载 重写 ⑦throw throws 运算符 public static void main(String[] args) {int a 1;System.out.println(a);System.out.println(a);}在后&#xff…

Node.js -- path模块

path.resolve(常用) // 导入fs const fs require(fs); // 写入文件 fs.writeFileSync(_dirname /index.html,love); console.log(_dirname /index.html);// D:\nodeJS\13-path\代码/index.html 我们之前使用的__dirname 路径 输出的结果前面是正斜杠/ &#xff0c;后面部分是…

测试的分类(2)

目录 按照执行方式分类 静态测试 动态测试 按照测试方法 灰盒测试 按照测试阶段分类 单元测试 集成测试 系统测试 冒烟测试 回归测试 按照执行方式分类 静态测试 所谓静态测试就是不实际运行被测软件,只是静态地检查程序代码, 界面或文档中可能存在错误的过程. 不以…

Git | 分支管理

Git | 分支管理 文章目录 Git | 分支管理1、理解分支2、创建分支&&切换分支3、合并分支4、删除分支5、合并冲突6、分支管理策略合并分支模式实际工作中分支策略bug分支删除临时分支 1、理解分支 分支就类似分身。 在版本回退中&#xff0c;每次提交Git都会将修改以git…

.net core webapi 高颜值的接口管理系统界面取代swagger,更好调试和查看

.net core webapi 高颜值的接口管理系统界面取代swagger&#xff0c;更好调试和查看 安装 dotnet add package IGeekFan.AspNetCore.Knife4jUI --version 0.0.16配置文档&#xff1a; 配置起始页 builder.Services.AddSwaggerGen(c > {// 配置 Swagger 文档相关信息c.Swa…

圣若热城堡、贝伦塔、热罗尼莫斯修道院 BIBM 2024在里斯本等你

会议之眼 快讯 2024年BIBM&#xff08;IEEE International Conference on Bioinformatics and Biomedicine&#xff09;即IEEE生物信息学与生物医学国际会议将于 2024年 12月3日-6日在葡萄牙里斯本举行&#xff01;这个会议由IEEE&#xff08;电气和电子工程师协会&#xff09…

CCF PTA 2023年11月C++卫星发射

【问题描述】 在 2050 年卫星发射技术已经得到极大发展&#xff0c;我国将援助 A 国建立远轨道卫星导航系统&#xff0c;该项目计划第 一个天发射一颗卫星&#xff1b;之后两天&#xff08;第二天和第三天&#xff09;&#xff0c;每天发射两颗卫星&#xff1b;之后三天&#…