【C++】—— 日期类的实现

【C++】------ 日期类的实现

文章目录

  • [【C++】------ 日期类的实现](#【C++】—— 日期类的实现)
    • 前言
    • [1. 声明和定义分离](#1. 声明和定义分离)
    • [2. 日期加天数(日期类 += 整数)](#2. 日期加天数(日期类 += 整数))
    • [3. 日期加天数(日期类 + 整数)](#3. 日期加天数(日期类 + 整数))
    • [4. 日期减天数(日期类 -= 整数/日期类 - 整数)](#4. 日期减天数(日期类 -= 整数/日期类 - 整数))
    • [5. 日期类对比](#5. 日期类对比)
      • [5.1 日期 < 日期](#5.1 日期 < 日期)
      • [5.2 日期 == 日期](#5.2 日期 == 日期)
      • [5.3 其他日期类比较(比较复用)](#5.3 其他日期类比较(比较复用))
    • [6. 前置++和后置++](#6. 前置++和后置++)
    • [7. 日期类相减(日期类-日期类)](#7. 日期类相减(日期类-日期类))
    • [8. 日期类的 IO](#8. 日期类的 IO)
    • 结语

前言

学了一些类和对象的知识大家是不是感觉云里雾里的

今天我们就来一篇轻松一点的内容,来通过之前学过的知识,试写一个日期类,巩固一下之前的知识

1. 声明和定义分离

我们想让 .h 放函数的声明。.cpp放函数的定义

CPP 复制代码
#pragma once

#include<iostream>
#include<assert.h>
using namespace std;

class Date
{
	// 友元函数
	friend istream& operator>>(istream& in, Date& d);
	friend ostream& operator<<(ostream& out, const Date& d);

public:
	bool CheckDate() const;

	Date(int year = 1900, int month = 1, int day = 1);

	void Print() const;

	// 默认是内联函数inline
	int GetMonthDay(int year, int month) const
	{
		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;
		}

		return monthDayArray[month];
	}

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

	Date operator-(int day) const;
	Date& operator-=(int day);

	Date operator++(int);//后置
	Date& operator++();//前置
	Date operator--(int);//后置
	Date& operator--();//前置

	int operator-(const Date& d) const;

private:
	int _year;
	int _month;
	int _day;
};

istream& operator>>(istream& in, Date& d);
ostream& operator<<(ostream& out, const Date& d);

日期类主要实现他的比较和日期类之间的相互运算

让我们一起来看看吧

2. 日期加天数(日期类 += 整数)

思路:先将整数加到天数上,如果天数不超过当月天数,直接返回即可

否则说明日期比当月的所有日期都大,则向下一个月借位,天数减去当月天数之和,以此类推知道天数不超过当月的最大天数位置

如果12借位则年份+1,月份改为1即可

代码如下:

CPP 复制代码
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;
}

Date& Date::operator+=(int day) 递了一个 Date 类型的引用,为什么

从整体来看,使用引用的方式是为了优化性能、允许链式调用、直接修改对象以及保持代码的清晰和一致性

3. 日期加天数(日期类 + 整数)

思路 :我们实现日期类+整数,也就是不改变日期类,返回日期类+=整数的结果

那我们可以复用日期类+=整数的逻辑

为了不修改日期类,我们对日期类拷贝一份tmp,让tmp进行+=的逻辑这样改变就不会日期类

代码如下:

CPP 复制代码
Date Date::operator+(int day) const
{
	Date tmp = *this;
	tmp += day;

	return tmp;
}

Date Date::operator+(int day) const 设计成返回一个新对象而不是引用是为了符合 + 运算符的语义

使用值返回可以确保调用者获得一个新的 Date 对象,而不会影响到原始对象

4. 日期减天数(日期类 -= 整数/日期类 - 整数)

这里思路和我们前面实现+的思路一样。都是通过借位的思想。我们向当天数 -day。

然后当天数 <0 时,向上一个月借位,天数 += 上个月的天数(注意是上个月的,因为当月的天数已经被减过了),如果是1月的话,借去年12月的天数,让月份=12,然后年份---

代码如下:

CPP 复制代码
Date& Date::operator-=(int day)
{
	if (day < 0)
	{
		return *this += (-day);
	}

	_day -= day;
	while (_day < 0)
	{
		--_month;
		if (_month == 0)
		{
			_month = 12;
			--_year;
		}

		_day += GetMonthDay(_year, _month);
	}

	return *this;
}

像日期类 + 整数一样,日期类 - 整数我们就复用 -= 即可

代码如下:

CPP 复制代码
Date Date::operator-(int day) const
{
	Date tmp = *this;
	tmp -= day;

	return tmp;
}

5. 日期类对比

5.1 日期 < 日期

判断日期 < 日期

先比较年, < 返回true

再继续比较月, < 返回true

最后比较天

剩下的情况都是false的情况。直接返回false

代码如下:

CPP 复制代码
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;
		}
	}
}

5.2 日期 == 日期

判断两个日期类很简单,我们只需要判断是否他们的年月日都相等即可

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

5.3 其他日期类比较(比较复用)

剩下的我们可以不需要自己再写一遍代码,直接通过前面实现的 < 和 == 复用即可

其他运行代码如下:

CPP 复制代码
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);
}

6. 前置++和后置++

前置我们拷贝一份*this,在复用+=或-=即可

前置++ :直接对当前对象执行自增操作,*this += 1;,修改对象的日期

后置++ :为了区分前置和后置自增运算符,后置版本通常接受一个 int 参数

代码如下:

CPP 复制代码
// d1++
// d1.operator++(0)
Date Date::operator++(int)
{
	Date tmp = *this;
	*this += 1;

	return tmp;
}

// ++d1
// d1.operator++()
Date& Date::operator++()
{
	*this += 1;

	return *this;
}

前置--和后置--同理:

CPP 复制代码
Date Date::operator--(int)
{
	Date tmp = *this;
	*this -= 1;
    
	return tmp;
}

Date& Date::operator--()
{
	*this -= 1;
    
	return *this;
}

7. 日期类相减(日期类-日期类)

两个日期类相减得出他们之间相差的天数

思路:直接让小的天数一直相加,直到相加到小的日期和大的日期相等即可,每次日期++就用一个变量记录天数即可

CPP 复制代码
// d1 - d2
int Date::operator-(const Date& d) const
{
	int flag = 1;
	Date max = *this;
	Date min = d;
	if (*this < d)
	{
		max = d;
		min = *this;
		flag = -1;
	}

	int n = 0;
	while (min != max)
	{
		++min;
		++n;
	}

	return n * flag;
}

8. 日期类的 IO

因为类的成员函数默认*this抢占了第一个位置,和我们平时的写法不一样,所以我们把日期类的输出和输出放在类外面,那放在类外面我们如何访问类的成员变量呢?那我们就可以加一个友元函数声明,后续的内容也会讲到的,现在了解即可

代码如下:

CPP 复制代码
ostream& operator<<(ostream& out, const Date& d)
{
	out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
	return out;
}

istream& operator>>(istream& in, Date& d)
{
	while (1)
	{
		cout << "请依次输入年月日:";
		in >> d._year >> d._month >> d._day;

		if (!d.CheckDate())
		{
			cout << "输入日期非法:";
			d.Print();
			cout << "请重新输入!!!" << endl;
		}
		else
		{
			break;
		}
	}

	return in;
}

当你将对象作为参数传递时,默认情况下会进行拷贝,这意味着会创建一个对象的副本。如果对象很大(例如,包含多个成员变量或复杂数据结构),这会导致性能问题。通过传递引用,你可以避免这个拷贝过程,从而提高性能

对于输入运算符重载 operator>>,我们需要修改传入的 Date 对象来设置其年、月、日。如果你通过值传递,那么在函数内对参数的修改不会影响到原始对象。使用引用则允许我们直接修改原始对象

传递引用,特别是在涉及到大型对象时,可以显著提高性能,同时能够方便地对对象进行操作。常量引用的使用则在确保对象不被修改的同时,仍能高效地进行读取操作。这些设计原则在 C++ 编程中是相当常见的,尤其是在处理自定义类型时

通过这些设计,Date 类能够有效地与用户进行交互,实现便捷的日期输入和输出功能

结语

今天的内容大家感觉怎么样呢,是不是还是比较轻松的

好了,感谢你能看到这里,后面我会附上源代码,供大家参考,要是有好的想法也可以在评论区讨论,溜了溜了,我们下期再见吧

源代码

Date.h:

CPP 复制代码
#pragma once

#include<iostream>
#include<assert.h>
using namespace std;

class Date
{
	// 友元函数
	friend istream& operator>>(istream& in, Date& d);
	friend ostream& operator<<(ostream& out, const Date& d);

public:
	bool CheckDate() const;

	Date(int year = 1900, int month = 1, int day = 1);

	void Print() const;

	// 默认是内联函数inline
	int GetMonthDay(int year, int month) const
	{
		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;
		}

		return monthDayArray[month];
	}

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

	Date operator-(int day) const;
	Date& operator-=(int day);

	Date operator++(int);//后置
	Date& operator++();//前置
	Date operator--(int);//后置
	Date& operator--();//前置

	int operator-(const Date& d) const;

private:
	int _year;
	int _month;
	int _day;
};

istream& operator>>(istream& in, Date& d);
ostream& operator<<(ostream& out, const Date& d);

Date.cpp:

CPP 复制代码
#define  _CRT_SECURE_NO_WARNINGS

#include"Date.h"

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

Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;

	if (!CheckDate())
	{
		cout << "非法日期:";
		Print();
	}
}

// void Date::Print(const Date* const this)
void Date::Print() const
{
	cout << _year << "/" << _month << "/" << _day << endl;
}

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

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 _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

bool Date::operator!=(const Date& d) const
{
	return !(*this == d);
}

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

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

	return tmp;
}

Date& Date::operator-=(int day)
{
	if (day < 0)
	{
		return *this += (-day);
	}

	_day -= day;
	while (_day < 0)
	{
		--_month;
		if (_month == 0)
		{
			_month = 12;
			--_year;
		}

		_day += GetMonthDay(_year, _month);
	}

	return *this;
}

Date Date::operator-(int day) const
{
	Date tmp = *this;
	tmp -= day;

	return tmp;
}

// d1++
// d1.operator++(0)
Date Date::operator++(int)
{
	Date tmp = *this;
	*this += 1;

	return tmp;
}

// ++d1
// d1.operator++()
Date& Date::operator++()
{
	*this += 1;

	return *this;
}

Date Date::operator--(int)
{
	Date tmp = *this;
	*this -= 1;
    
	return tmp;
}

Date& Date::operator--()
{
	*this -= 1;
    
	return *this;
}

// d1 - d2
int Date::operator-(const Date& d) const
{
	int flag = 1;
	Date max = *this;
	Date min = d;
	if (*this < d)
	{
		max = d;
		min = *this;
		flag = -1;
	}

	int n = 0;
	while (min != max)
	{
		++min;
		++n;
	}

	return n * flag;
}

ostream& operator<<(ostream& out, const Date& d)
{
	out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
	return out;
}

istream& operator>>(istream& in, Date& d)
{
	while (1)
	{
		cout << "请依次输入年月日:";
		in >> d._year >> d._month >> d._day;

		if (!d.CheckDate())
		{
			cout << "输入日期非法:";
			d.Print();
			cout << "请重新输入!!!" << endl;
		}
		else
		{
			break;
		}
	}

	return in;
}
相关推荐
数据分析螺丝钉3 分钟前
力扣第240题“搜索二维矩阵 II”
经验分享·python·算法·leetcode·面试
no_play_no_games3 分钟前
「3.3」虫洞 Wormholes
数据结构·c++·算法·图论
￴ㅤ￴￴ㅤ9527超级帅3 分钟前
LeetCode hot100---数组及矩阵专题(C++语言)
c++·leetcode·矩阵
五味香3 分钟前
C++学习,信号处理
android·c语言·开发语言·c++·学习·算法·信号处理
梓䈑20 分钟前
【C语言】自定义类型:结构体
c语言·开发语言·windows
PYSpring25 分钟前
数据结构-LRU缓存(C语言实现)
c语言·数据结构·缓存
毕小宝27 分钟前
逻辑回归(下): Sigmoid 函数的发展历史
算法·机器学习·逻辑回归
小叮当爱咖啡33 分钟前
DenseNet算法:口腔癌识别
算法
qq_4218336735 分钟前
计算机网络——应用层
笔记·计算机网络
希望有朝一日能如愿以偿36 分钟前
算法(食物链)
算法