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


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

🔥个人主页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.mfbz.cn/a/557009.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

鸿蒙开发语言_ArkTS开发语言体验_TypeScript语言环境搭建_TS声明和数据类型---HarmonyOS4.0+鸿蒙NEXT工作笔记003

可以看到我们新建的这个项目,有个 @State message: String =Hello ArkTS 这个就是定义了一个变量,可以看到 message是变量名,String是变量类型. 然后我们可以看看它的结构可以看到 build() 下面有个Row,然后再下面有个Column方法,然后,里面就是具体的内容了,首先就是显示了一…

高速公路车型识别系统的新篇章:激光雷达解决方案的探索与应用

高速公路车型识别系统&#xff1a;激光雷达解决方案的探索与应用 随着智能交通领域的迅速发展&#xff0c;高速公路车型识别技术成为提高交通管理效率与安全性的关键一环。激光雷达作为一种高精度、高可靠性的传感器技术&#xff0c;在高速公路车型识别中展现出巨大的应用潜力…

华强电子网(www.hqew.com)2023年度电子行业优秀国产品牌企业评选

华强电子网&#xff08;www.hqew.com&#xff09;2023年度电子行业优秀国产品牌企业评选&#xff0c;历经四个月的激烈竞争和严格审核&#xff0c;经过企业提名、专家筛选、公众投票和专家评审四大阶段&#xff0c;近千家电子行业企业成功提名&#xff0c;其中有超过200家国产品…

像经典编程一样简单!MIT科学家开发新型量子计算机模型

量子计算软件市场预计将迎来指数级增长&#xff0c;预测到2030年其复合年增长率&#xff08;CAGR&#xff09;将达到21.9%。这不仅预示着前所未有的计算能力的解放&#xff0c;而且能够帮助各行各业解决极其复杂的问题。 量子计算软件包括一系列工具、算法和编程语言&#xff0…

Training - PyTorch Lightning 的 Horovod 策略实践 (all_gather)

欢迎关注我的CSDN&#xff1a;https://spike.blog.csdn.net/ 本文地址&#xff1a;https://blog.csdn.net/caroline_wendy/article/details/137686312 在 PyTorch Lightning 中使用 Horovod 策略&#xff0c;可以在多个 GPU 上并行训练模型。Horovod 是分布式训练框架&#xff…

Linux sudo suid提权练习

题目比较简单&#xff0c;可以利用sudo和多种suid程序提权&#xff0c;做个记录 进入靶场题目环境 获得节点信息 远程连接上 执行命令id&#xff0c;发现只是admin普通账户 sudo提权 发现存在 /usr/bin/vim, /usr/bin/bash, /usr/bin/more, /usr/bin/less, /usr/bin/nano, /…

CSS入门:link链接样式和4种状态的详解

你好&#xff0c;我是云桃桃。 一个希望帮助更多朋友快速入门 WEB 前端的程序媛。 云桃桃-大专生&#xff0c;一枚程序媛&#xff0c;感谢关注。回复 “前端基础题”&#xff0c;可免费获得前端基础 100 题汇总&#xff0c;回复 “前端工具”&#xff0c;可获取 Web 开发工具…

React + 项目(从基础到实战) -- 第九期

实现分页 , LoadMore 上划加载更多功能效果 分页 page : 当前页 pageSize: 页面大小 自定义分页组件 组件传值 import {FC , useEffect, useState } from reactimport { useNavigate , useLocation ,useSearchParams} from react-router-dom;import { Pagination } from &quo…

每日两题3

礼物最大价值 class Solution { public:int jewelleryValue(vector<vector<int>>& frame) {int m frame.size(),n frame[0].size();vector<vector<int>> dp(m1,vector<int>(n1,0));for(int i 1; i < m;i){for(int j 1; j < n;j){d…

轻松点餐|餐饮小程序新玩法,美食触手可及

在企业经营领域&#xff0c;小程序正成为越来越多行业开展线上经营的重要工具。依托小程序等工具自主开发数字化经营平台&#xff0c;已经成为零售、餐饮等日常消费行业的趋势。餐饮行业向智能化快速迭代已势在必行&#xff0c;在此进程中&#xff0c;小程序成为了备受餐饮商家…

Mysql嵌套查询太简单了

1、子查询的分类 不相关查询&#xff1a; 子查询能独立执行 相关查询&#xff1a; 子查询不能独立运行 相关查询的执行顺序&#xff1a; 首先取外层查询中表的第一个元组,根据它与内层查询相关的属性值处理内层查询, 若WHERE子句返回值为真&#xff0c;则取此元组放入结果…

SpringBoot整合PDF动态填充数据并下载

目录 目录 一、准备环境 二、iTextPDF介绍 三、步骤 四、访问查看结果 五、源代码参考 一、准备环境 ①下载一个万兴pdf软件 ②准备一个pdf 文件 二、iTextPDF介绍 这是一个用于生成PDF文档的Java库&#xff0c; 文档创建与修改&#xff1a;iTextPDF能够从零开始创建…

2024红明谷杯——Misc 加密的流量

2024红明谷杯——Misc 加密的流量 写在前面&#xff1a; 这里是贝塔贝塔&#xff0c;照例来一段闲聊 打比赛但赛前一波三折&#xff0c;又是成功签到的一个比赛 说起来比赛全名叫红明谷卫星应用数据安全场景赛&#xff0c;但好像真的跟卫星的关系不大&#xff0c;没有bin方…

面试Spring框架

什么是Spring框架&#xff1f; Spring框架是一个开源的Java应用程序框架&#xff0c;提供了综合的基础设施支持&#xff0c;用于开发Java企业应用程序。它涵盖了从基本的核心容器到全面的企业服务&#xff0c;可以用于构建任何规模的应用程序。 Spring框架的核心特性是什么&am…

Go之map详解

map的结构 map实现的两个关键数据结构 hmap 定义了map的结构bmap 定义了hmap.buckets中每个bucket的结构 // A header for a Go map. type hmap struct {count int // 元素的个数flags uint8 // 状态标记&#xff0c;标记map当前状态&#xff0c;是否正在写入B …

<计算机网络自顶向下> 可靠数据传输的原理(未完成)

可靠数据传输&#xff08;rdt&#xff1a;Reliable Data Transfer&#xff09;的原理 rdt在应用层&#xff0c;传输层和数据链路层都很重要是网络TOP10问题之一信道的不可靠特点决定了可靠数据传输rdt的复杂性rdt_send: 被上层&#xff08;如应用层&#xff09;调用&#xff0…

41.缺失的第一个正数

1. 解题原理&#xff1a; &#xff08;1&#xff09;对于一个有序的、不缺失元素的正数数组nums&#xff0c;元素nums[i]应当位于nums[i]-1的位置处。 &#xff08;2&#xff09;nums数组的长度为N&#xff0c;缺失的第一个正数如果不位于[1,N]&#xff0c;那么就肯定是N1 2. …

excel表格怎么设置密码?excel文件加密的两个方法

一、加密码的原理​ Excel加密码的原理主要基于加密算法和密钥管理。当用户为Excel文件或工作表设置密码时&#xff0c;Excel会采用一种加密算法对文件或工作表进行加密处理。这种加密算法通常是对称加密算法&#xff0c;如AES(高级加密标准)或DES(数据加密标准)。 二&#x…

海外住宅代理:推特账号为何容易被关小黑屋?

推特是全球最受欢迎的社交媒体之一&#xff0c;每天都有数以百万计的用户在这个平台上发布信息、分享观点和交流互动。然而&#xff0c;有些用户可能会发现他们的推特账号不幸陷入了所谓的“关小黑屋”状态&#xff0c;即账号被限制了可见度&#xff0c;导致发布的内容无法被其…

【数据分析面试】24.20个数据库问答题 (考察数据开发和实际应用能力)

作为数据从业者&#xff0c;日常工作除了对各类业务数据进行分析挖掘&#xff0c;也需要经常和数据库打交道、甚至也少不了要承担一些数据开发、数仓管理的工作。掌握数据库管理的基本概念和技术是至关重要的。无论是初学者还是从业者&#xff0c;理解数据库索引、范式、事务、…
最新文章