《详解 C++ Date 类的设计与实现:从运算符重载到功能测试》
代码语言:javascriptAI代码解释。
前言: 这篇博客主要会介绍一下Date类的实现,需要运用到前面学习的一些C++的知识。同时,也可以通过这个小练习来检验一下自己的学习成果,我会先把.h文件放在前言后面,大家可以自己先去实现一下试试,再来看看博主的文章。
Date.h:
代码语言:javascript
AI代码解释
#pragma once
class Date
{
public:
// 获取某年某月的天数
int GetMonthDay(int year, int month);
// 全缺省的构造函数
Date(int year = 1900, int month = 1, int day = 1);
// 拷贝构造函数
// d2(d1)--this
//Date(const Date& d);
// 赋值运算符重载--其实也可以不写
// d2 = d3 -> d2.operator=(&d2, d3)
Date& operator=(const Date& d);
// 析构函数
/*~Date();*/
// 日期+=天数
Date& operator+=(int day);
// 日期+天数
Date operator+(int day);
// 日期-天数
Date operator-(int day);
// 日期-=天数
Date& operator-=(int day);
// 前置++
Date& operator++();
// 后置++
Date operator++(int);
// 后置--
Date operator--(int);
// 前置--
Date& operator--();
// >运算符重载
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);
// 日期-日期 返回天数
int operator-(const Date& d);
//打印
void Print();
private:
int _year;
int _month;
int _day;
};
注意:博客中像打印,析构,拷贝,构造,赋值运算符重载这些之前实现过很多次的就不会再出现了,大家可以自己去实现一下(当然Date类的析构,拷贝,赋值运算符重载都是可以不写的),最后也可以直接在代码总结里面看哈 。
目录
一.Date类+=和+的运算符重载实现与复用
1.1 +=
1.2 +
1.3 复用
+复用+=:
+=复用+:
对比图:编辑
test.cpp:
二.Date类-和-=的运算符重载实现与复用
2.1 -=
2.2 -
test.cpp:
三.Date类前置++,--与后置++,--的运算符重载实现
3.1 前置++
3.2 后置++
test.cpp:
3.3 前置--
3.4 后置--
test.cpp:
四.Date类比较符号的运算符重载实现
4.1 ==
4.2 >
4.3 >=
4.4 <
4.5 <=
4.6 !=
test.cpp:
五.Date类日期-日期的重载实现
日期-日期
test.cpp:
六.代码总览
Date.h:
Date.cpp:
test.cpp:
补充:
判断日期是否合法:
流插入:
流提取:
一.Date类+=和+的运算符重载实现与复用
1.1 +=
--我们在实现日期+=天数之间,还是需要先实现一个获取每月天数的函数的,这个可以直接在.h里面写,比较简单,这里就直接展示给大家看了。
代码语言:javascript
AI代码解释
// 获取某年某月的天数
int GetMonthDay(int year, int month)
{
assert(month > 0 && month < 13);
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];
}
}
在有了这个函数之后,我们就可以直接实现+=的重载了,注意分文件写的时候.cpp里面需要带上类域
代码语言:javascript
AI代码解释
//日期+=天数
Date& Date::operator+=(int day)
{
_day += day;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
++_month;
if (_month == 13)
{
++_year;
_month = 1;
}
}
//this出了作用域还在,所以可以用引用返回,减少拷贝
return *this;
}
思路: --因为是+=所以原来的也会改变,不需要先拷贝一份。我们直接让当前日期的天数加上给的天数,然后进入循环,直到日期合规为止。在循环里每次减掉当月的天数,再++month。当月份达到13时就加年然后把月置为1。就这样,当循环结束时,返回*this(可以使用引用返回)
更多推荐

所有评论(0)