【C++】实现日期类相关接口
C++语法 | 相关知识点 | 可以通过点击 | 以下链接进行学习 | 一起加油! |
---|---|---|---|---|
命名空间 | 缺省参数与函数重载 | C++相关特性 | 类和对象-上篇 | 类和对象-中篇 |
类和对象-下篇 |
本篇将介绍实现日期类中众多接口,同时这其中涉及到很多知识,务必将类和对象相关内容掌握再来实现日期类相关接口。
🌈个人主页:是店小二呀
🌈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++语言旅途中有所帮助!