当前位置: 首页 > news >正文

【C++】实现日期类相关接口

在这里插入图片描述

C++语法相关知识点可以通过点击以下链接进行学习一起加油!
命名空间缺省参数与函数重载C++相关特性类和对象-上篇类和对象-中篇
类和对象-下篇

本篇将介绍实现日期类中众多接口,同时这其中涉及到很多知识,务必将类和对象相关内容掌握再来实现日期类相关接口。

请添加图片描述
Alt
🌈个人主页:是店小二呀
🌈C语言笔记专栏:C语言笔记
🌈C++笔记专栏: C++笔记
🌈初阶数据结构笔记专栏: 初阶数据结构笔记
🌈Linux笔记专栏: Linux笔记

🌈喜欢的诗句:无人扶我青云志 我自踏雪至山巅 请添加图片描述

文章目录

  • 一、天数加法
  • 二、获得某年某月的天数
  • 三、比较两个日期
  • 四、日期加天数
    • 4.1 先实现operator+还是operator+=
  • 五、日期减日期
  • 六、流插入和流提取运算符重载
    • 6.1 需要判断输入进去的数据是否有误
  • 七、源代码展示
    • 7.1 Date.h
    • 7.2 Date.cpp
    • 7.3 test.cpp

如果你想让这个函数是内敛,可以在类里面定义的函数,默认是内敛,内敛不支持声明和定义分离。接下来我们将展开相关接口的实现逻辑。

一、天数加法

//前置++
Date& operator++(){_day += 1;return *this;}	
//后置++
Date operator++(int){Date temp(*this);_day += 1;return temp;}
int main()
{Date d;Date d1(2022, 1, 13);d = d1++; // d: 2022,1,13 d1:2022,1,14d = ++d1; // d: 2022,1,15 d1:2022,1,15return 0;
}
  • 前置++:返回对象+1后结果,由于this指针指向的对象,函数结束后不会销毁,故而使用引用方式返回,提高效率。
  • 后置++;既要完成对象+1操作,又要返回旧值的对象。这里可以使用拷贝构造一份this。对于temp属于临时对象,出了函数作用域就会销毁,因此只能传值返回,不能返回引用
  • 侧面反映了this虽然不能在参数部分显式写,但是可以在函数体内使用,这样子设计是有需求的。

二、获得某年某月的天数

关于计算日期,最频繁调用就是获得某年某月的天数接口,对此可以单独使用该接口。由于表示年月日的成员对象都在日期类中封装起来,类外部不能随便访问类成员,只能在类中实现GetMonthDay函数,在通过return将获得的天数返回。

实现逻辑(涉及到很多历史发展背景,这里局限于现代的日期计算):

int Date::GetMonthDay(int year, int month) const
{assert(month > 0 && month < 13);//保证月数合法static int montharr[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;elsereturn montharr[month];
}

实现上一些细节:

  • 这里由于自转和公转问题,当是闰年时,二月的天数加一
  • 还有一些细节上的问题(但是CPU跑太快,没啥影响),static int montharr属于静态变量,只能定义一次。对此频繁调用时,不用多次定义。
  • 在判断语句中,可以将位置进行调正,这里跟&&短路知识点有关,如果前面是假,不同接下去判断,整个表达式都为假

三、比较两个日期

这里需要涉及到运算符重载,这里有个小技巧,只需要实现大于等于或小于等于的接口。

函数声明

	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;

实现小于等于(剩下可取反)

bool Date::operator==(const Date& d) const
{return _year == d._year && _month == d._month && _day == d._day;
}bool Date::operator!=(const Date& d) const
{return !(*this == d);//这里会调用的
}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;elsereturn 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);
}

四、日期加天数

这里需要考虑持续进位原则

Date& Date::operator+=(int 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 temp(*this);//拷贝构造temp += day;return temp;
}
  • 当日期加完天数后,通过日期的规则需要按照进位原则,对年月日数据进行调正
  • 在实现operator+=/+,都可以间接实现operator+/+=
  • 这里operator+=使用日期加天数,提高了效率和避免传值返回中的拷贝过程
  • operator+这里不能使用引用返回,这里是创建了一个临时变量,调用完会销毁

4.1 先实现operator+还是operator+=

  • 先实现operator+=,再间接实现operator+呢?
  • 还是先实现operator+,再间接实现operator+=呢?

在这里插入图片描述

对此得出结论:推荐先实现operator+=,再间接实现operator+。

理由:

  • 将代码贴出来,方便进行对比。这里不能交叉对比,需要采用横向对比。
  • 两者实现operator+是等价,但是实现operator+=,左边需要复用+operator,相比之下多次拷贝构造。
  • 这不详细介绍关于operator-和operator-=。大体逻辑跟operator+和operator+有异曲同工之处(具体在Date.cpp看看)

五、日期减日期

需要使用持续借位原则,如果天数为0,需要得到上月的天数

第一种方式:不断++直到等于大的那个年份,这里需要日期加日期接口的技术支撑

int Date::operator-(const Date& d)
{int flag = 1;Date max = *this;Date min = d;if (*this < d){int flag = -1;//判断两个天数相差max = d;min = *this;}int n = 0;while (min != max){++min;//这里会调用operato++()++n;//operator++()}return n * flag;
}
  • 优点:方便实现
  • 缺点:效率低

第二个方法:通过该变量记录两个年份修饰到1月1日,也就是都修饰到1月1日之间还差多少天,再计算两个年之间有多少个年,如果是平年+365,闰年+366

int Date::operator-(const Date& d) const
{//不知道哪个操作数大,先假设Date max = *this;Date min = d;int flag = 1;if (*this < d)//假设错了就认错{Date max = d;Date min = *this;int flag = -1;//用来标记}int count =0;//大的减到1月1日  count++while (!(max._day == 1 && max._month == 1)){--max;++count;}//小的减到1月1日  count--while (!(min._day == 1 && min._month == 1)){--min;--count;}//都减到1月1日了  算差多少年while (min._year != max._year){if (is_leapyear(min._year))count += 366;elsecount += 365;++min._year;}return flag * count;
}

六、流插入和流提取运算符重载

out和cin的本质是输入和输出流对象,对于<<和>>用于重载的运算符,从图可以得,cout属于ostream类,cin属于istream类,可以自动识别类型

对于我们可以在日期类中,实现<<和>>重载打印日期和提取日

int main()
{Date d1(2024, 3, 10);//void operator<<(ostream& out);//cout<<d1;d1 << cout;//->d1.operator<<(cout)->operator<<(const Date *d1,cout);return 0;
}
  • 如果使用运算符重载,隐含的this指针占用第一个参数的位置,Date必须是左操作数,d1<<cout是不符合我们的习惯的
  • 对此我们可以在类外实现该运算符重载函数,就可以自己设计参数部分的位置
  • 但是又引出了另一个问题:类外不能访问类中的私有成员,如果将私有权限放开,就缺乏安全性,对此C++中有友元,接下来我们会涉及到,这里就使用下,虽然这个全局函数不在类中,但是可以访问私有成员函数
//友元,告诉该类这两个全局函数是我们的朋友,允许使用私有成员(在类中)friend ostream& operator<<(ostream& out, const Date& d);friend istream& operator>>(istream& in, Date& d);ostream& operator<<(ostream& out, const Date& d)
{out << d._year << "" << d._month << "" << d._day << "" << endl;return out;
}istream& operator>>(istream& in, Date& d)
{in >> d._year >> d._month >> d._day;return in;
}

如果我们需要连续打印cout<<d1<<d2的话,这里就不合适的。因为这里的结合性是从左往右,cout<<d1会返回一个临时变量,那么这里运算符重载函数需要通过引用返回了。C++存在私有的,printf不支持自定义打印,cout本质实现所用类型的打印。

- **用引用做返回值,应对连续流插入和流提取
- 流提取不是不能对Date进行const修饰,需要通过键盘读取数据存储在成员变量

6.1 需要判断输入进去的数据是否有误

在这里插入图片描述

七、源代码展示

7.1 Date.h

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;class Date
{
public:Date(int year = 1, int month = 1, int day = 1);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);// d1 + 100Date& operator+=(int day);Date operator+(int day);// d1 - 100Date operator-(int day);Date& operator-=(int day);// ++d1Date& operator++();// 特殊处理:解决语法逻辑不自洽,自相矛盾的问题// d1++// 为了跟前置++区分,强行增加一个int形参,够成重载区分Date operator++(int);Date operator--(int);Date& operator--();// d1 - d2int operator-(const Date& d);// 本质就是inlineint GetMonthDay(int year, int month){assert(month > 0 && month < 13);static int monthDays[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };// 365   自转  公转  365 5+h// 366if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))){return 29;}return monthDays[month];}void Print(){cout << _year << "/" << _month << "/" << _day << endl;}
private:int _year;int _month;int _day;
};

7.2 Date.cpp

#include"Date.h"Date::Date(int year, int month, int day)
{_year = year;_month = month;_day = day;
}bool Date::operator<(const Date& d)
{if (_year < d._year){return true;}else if (_year == d._year){if (_month < d._month){return true;}else if (_month == d._month){if (_day < d._day){return true;}}}return false;
}
// d1 <= d2
bool Date::operator<=(const Date& d)
{return *this < d || *this == d;
}bool Date::operator>(const Date& d)
{return !(*this <= d);
}bool Date::operator>=(const Date& d)
{return !(*this < d);
}bool Date::operator==(const Date& d)
{return _year == d._year&& _month == d._month&& _day == d._day;
}bool Date::operator!=(const Date& d)
{return !(*this == d);
}// d1 += 10
Date& Date::operator+=(int 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)
{//Date tmp(*this);Date tmp = *this; // tmp += day;return tmp;
}// d1 + 10
//Date Date::operator+(int day)
//{
//	//Date tmp(*this);
//	Date tmp = *this; // 
//
//	tmp._day += day;
//	while (tmp._day > GetMonthDay(tmp._year, tmp._month))
//	{
//		tmp._day -= GetMonthDay(tmp._year, tmp._month);
//		++tmp._month;
//		if (tmp._month == 13)
//		{
//			++tmp._year;
//			tmp._month = 1;
//		}
//	}
//
//	return tmp;
//}
//
 d1 += 100
//Date& Date::operator+=(int day)
//{
//	*this = *this + day;
//
//	return *this;
//}Date Date::operator-(int day)
{Date tmp = *this;tmp -= day;return tmp;
}Date& Date::operator-=(int day)
{_day -= day;while (_day <= 0){--_month;if (_month == 0){--_year;_month = 12;}_day += GetMonthDay(_year, _month);}return *this;
}// ++d ->d.operator++()
Date& Date::operator++()
{*this += 1;return *this;
}// d++ ->d.operator++(0)
Date Date::operator++(int)
{Date tmp = *this;*this += 1;return tmp;
}// d1 - d2
int Date::operator-(const Date& d)
{int flag = 1;Date max = *this;Date min = d;if (*this < d){int flag = -1;max = d;min = *this;}int n = 0;while (min != max){++min;++n;}return n * flag;
}

7.3 test.cpp

#define _CRT_SECURE_NO_WARNINGS 1
#include "Date.h"int main()
{Date d1(2024, 1, 29);Date d2 = d1 + 20;d2.Print();d1.Print();d2 -= 20;d2.Print();d1 += 30000;d1.Print();++d1;d1.operator++();d1.Print();d1++;d1.operator++(10);d1.Print();/*bool ret = false;if (ret){d1.Print();}*/Date d4(2024, 1, 29);Date d5(2024, 8, 1);cout << d5 - d4 << endl;return 0;
}

以上就是本篇文章的所有内容,在此感谢大家的观看!这里是店小二呀C++笔记,希望对你在学习C++语言旅途中有所帮助!
请添加图片描述

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 第131天:内网安全-横向移动Kerberos 攻击SPN扫描WinRMWinRSRDP
  • 【Python学习-UI界面】PyQt5 小部件1-Label
  • 一款专为IntelliJ IDEA用户设计的插件,极大简化Spring项目中的API调试过程,功能强大(附源码)
  • Unity Dots学习 (一)
  • 多媒体技术及应用课程思政网站
  • 为何用新版本的Supra软件,FPGA引脚输出不正常
  • 深入探索 MyBatis
  • 【车载开发系列】常见单片机烧录与调试设备
  • RTT学习
  • Python密码生成器
  • [C#]OpenCvSharp 实现Bitmap和Mat的格式相互转换
  • 分享一个基于微信小程序的宠物服务中心的设计与实现(源码、调试、LW、开题、PPT)
  • python——元组解包
  • 机器学习第五十二周周报 Distribution Shift of GNN
  • tomcat 运行javaweb项 提示无法将资源添加到Web应用程序缓存解决方法
  • @jsonView过滤属性
  • 【Redis学习笔记】2018-06-28 redis命令源码学习1
  • 【附node操作实例】redis简明入门系列—字符串类型
  • 10个最佳ES6特性 ES7与ES8的特性
  • angular组件开发
  • Bootstrap JS插件Alert源码分析
  • Java 9 被无情抛弃,Java 8 直接升级到 Java 10!!
  • Javascript Math对象和Date对象常用方法详解
  • JS进阶 - JS 、JS-Web-API与DOM、BOM
  • Linux编程学习笔记 | Linux多线程学习[2] - 线程的同步
  • linux学习笔记
  • MD5加密原理解析及OC版原理实现
  • Node.js 新计划:使用 V8 snapshot 将启动速度提升 8 倍
  • node入门
  • -- 查询加强-- 使用如何where子句进行筛选,% _ like的使用
  • 道格拉斯-普克 抽稀算法 附javascript实现
  • 复习Javascript专题(四):js中的深浅拷贝
  • 回顾2016
  • 看完九篇字体系列的文章,你还觉得我是在说字体?
  • 每天10道Java面试题,跟我走,offer有!
  • 排序(1):冒泡排序
  • 排序算法之--选择排序
  • 腾讯大梁:DevOps最后一棒,有效构建海量运营的持续反馈能力
  • 东超科技获得千万级Pre-A轮融资,投资方为中科创星 ...
  • 选择阿里云数据库HBase版十大理由
  • 支付宝花15年解决的这个问题,顶得上做出十个支付宝 ...
  • ​经​纬​恒​润​二​面​​三​七​互​娱​一​面​​元​象​二​面​
  • #我与Java虚拟机的故事#连载05:Java虚拟机的修炼之道
  • (2009.11版)《网络管理员考试 考前冲刺预测卷及考点解析》复习重点
  • (Redis使用系列) Springboot 整合Redisson 实现分布式锁 七
  • (分布式缓存)Redis哨兵
  • (附源码)ssm码农论坛 毕业设计 231126
  • (回溯) LeetCode 46. 全排列
  • (免费领源码)python#django#mysql公交线路查询系统85021- 计算机毕业设计项目选题推荐
  • (一)appium-desktop定位元素原理
  • (一)eclipse Dynamic web project 工程目录以及文件路径问题
  • (源码分析)springsecurity认证授权
  • (转)从零实现3D图像引擎:(8)参数化直线与3D平面函数库
  • (转载)深入super,看Python如何解决钻石继承难题
  • .env.development、.env.production、.env.staging