日期类(完全讲解版)

发布于:2025-02-21 ⋅ 阅读:(17) ⋅ 点赞:(0)

 1. 类的设计思想

Date 类的设计目的是为了封装和处理日期信息,它提供了对日期的基本操作,如日期加减、日期比较、日期合法性检查等。类中的私有成员 int _year, int _month, int _day 存储了日期的年、月、日。

类的声明和构造

Date 类的声明:

#pragma once
#include<iostream>
using namespace std;

#include<assert.h>

// Date 类的声明
class Date
{
    // 友元函数声明:允许这两个函数访问 Date 类的私有成员
    // 用于重载输入和输出流运算符
    friend ostream& operator<<(ostream& out, const Date& d);
    friend istream& operator>>(istream& in, Date& d);

public:
    // 拷贝赋值运算符:用于将一个 Date 对象赋值给另一个 Date 对象
    Date& operator=(const Date& d);

    // 构造函数:初始化 Date 对象的年、月、日,默认值为 1900-01-01
    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 };

        // 如果是闰年且月份为 2,则返回 29 天
        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;

    // 计算两个日期之间的天数差
    int operator-(const Date& d) const;

    // 前置自增运算符:++d
    Date& operator++();

    // 后置自增运算符:d++
    // 使用 int 参数区分前置和后置版本,但参数值未使用
    Date operator++(int);

    // 前置自减运算符:--d
    Date& operator--();

    // 后置自减运算符:d--
    Date operator--(int);

private:
    int _year;  // 年
    int _month; // 月
    int _day;   // 日
};

// 重载输出流运算符 <<:将 Date 对象格式化输出到流中
ostream& operator<<(ostream& out, const Date& d);

// 重载输入流运算符 >>:从流中读取数据并赋值给 Date 对象
istream& operator>>(istream& in, Date& d);

函数实现

#define _CRT_SECURE_NO_WARNINGS 1
#include "Date.h"

// 检查日期是否合法
bool Date::CheckDate()
{
    // 如果月份不在 1~12 之间,或者天数不在 1~指定月份最大天数之间,返回 false
    if (_month < 1 || _month > 12
        || _day < 1 || _day > GetMonthDay(_year, _month))
    {
        return false;
    }
    else
    {
        return true;
    }
}

// 构造函数:全缺省构造函数
// 初始化年份、月份和天数,默认值为 1900-01-01
// 如果传入的日期不合法,输出提示信息
Date::Date(int year, int month, int day) {
    _year = year;
    _month = month;
    _day = day;
    if (!CheckDate()) {
        cout << "日期非法" << endl;
    }
}

// 拷贝构造函数(目前未实现,注释掉)
// Date::Date(const Date& d) {}

// 赋值运算符重载
// 用于将一个 Date 对象赋值给另一个
Date& Date::operator=(const Date& d)
{
    // 检查是否自赋值
    if (this != &d)
    {
        _year = d._year;
        _month = d._month;
        _day = d._day;
    }

    return *this; // 返回自身引用
}

// 日期 += 天数
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) { // 如果超出 12 月,增加一年并重置为 1 月
            ++_year;
            _month = 1;
        }
    }
    return *this;
}

// 日期 + 天数,返回新对象
Date Date::operator+(int day) const {
    Date tmp = *this;
    tmp += day; // 调用 += 运算符
    return tmp;
}

// 日期 - 天数,返回新对象
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) { // 如果减到 0 月,减少一年并设置为 12 月
            --_year;
            _month = 12;
        }
        _day += GetMonthDay(_year, _month); // 补足前一个月的天数
    }
    return *this;
}

// 前置自增 ++d
Date& Date::operator++() {
    *this += 1; // 日期加 1 天
    return *this;
}

// 后置自增 d++
Date Date::operator++(int) {
    Date tmp = *this; // 保存当前值
    *this += 1; // 日期加 1 天
    return tmp; // 返回旧值
}

// 前置自减 --d
Date& Date::operator--() {
    *this -= 1; // 日期减 1 天
    return *this;
}

// 后置自减 d--
Date Date::operator--(int) {
    Date tmp = *this; // 保存当前值
    *this -= 1; // 日期减 1 天
    return tmp; // 返回旧值
}

// > 运算符重载:判断当前日期是否大于另一个日期
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); // 使用 < 的逆结果
}

// < 运算符重载:判断当前日期是否小于另一个日期
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); // 使用 == 的逆结果
}

// 日期 - 日期,返回两个日期的天数差
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; // 返回天数差,带正负号
}

// 打印日期
void Date::Print() const {
    cout << _year << "年" << _month << "月" << _day << "日" << endl;
}

// 输出流运算符重载 <<:格式化输出日期
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;
}

2. 成员函数

着重讲一下这几个成员

2.1 构造函数构造函数

Date::Date(int year, int month, int day) {
    _year = year;
    _month = month;
    _day = day;
    if (!CheckDate()) {
        cout << "日期非法" << endl;
    }
}

构造函数的作用是初始化日期对象。当创建一个 Date 对象时,如果没有传入参数,它会默认初始化为 1900-01-01。如果传入了非法的日期(比如 2 月 30 日),会输出 "日期非法" 的错误信息。

2.2 CheckDate() 函数

CheckDate 是用于验证日期是否合法。它首先检查月份是否在 1~12 之间,然后检查日期是否在该月份的合法天数范围内。如果不合法,返回 false,否则返回 true

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

2.3 GetMonthDay() 函数

GetMonthDay() 用于返回指定年份和月份的天数。例如,2 月有 28 天,但如果是闰年则有 29 天。函数使用一个静态数组来存储每个月的天数(非闰年),并特别处理闰年的 2 月。

int Date::GetMonthDay(int year, int month) {
    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];
    }
}

这里使用静态数组 monthDayArray 来存储每个月的天数,方便在需要时快速返回指定月份的天数。对于 2 月,如果年份符合闰年条件,则返回 29 天。

2.4 赋值运算符 operator=

operator= 用于实现日期对象之间的赋值操作。这里的实现首先检查是否是自赋值(即对象和自己赋值),如果不是,才执行赋值操作。

Date& Date::operator=(const Date& d) {
    if (this != &d) {
        _year = d._year;
        _month = d._month;
        _day = d._day;
    }
    return *this;
}

3. 运算符重载

通过运算符重载,Date 类提供了强大的日期计算功能,使得日期加减、比较操作都变得非常直观。

3.1 日期加法和减法运算符重载

  • operator+=:将指定天数增加到当前日期,并处理跨月、跨年的情况。
  • operator+:使用 operator+= 来实现日期加法运算符的功能。
  • operator-=:将指定天数从当前日期中减去,处理跨月、跨年的情况。
  • operator-:使用 operator-= 来实现日期减法运算符的功能。
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) { // 如果超出 12 月,进入下一年
            ++_year;
            _month = 1;
        }
    }
    return *this;
}

3.2 前置和后置自增、前置和后置自减运算符

  • operator++():前置自增,将日期加 1 天,并返回当前对象的引用。
  • operator++(int):后置自增,先保存当前日期,再增加 1 天,返回原日期。
  • operator--():前置自减,将日期减去 1 天,并返回当前对象的引用。
  • operator--(int):后置自减,先保存当前日期,再减去 1 天,返回原日期。
Date& Date::operator++() {
    *this += 1; // 将当前日期增加 1 天
    return *this;
}

Date Date::operator++(int) {
    Date tmp = *this; // 保存当前日期
    *this += 1; // 日期增加 1 天
    return tmp; // 返回原日期
}

Date& Date::operator--() {
    *this -= 1; // 将当前日期减少 1 天
    return *this;
}

Date Date::operator--(int) {
    Date tmp = *this; // 保存当前日期
    *this -= 1; // 日期减少 1 天
    return tmp; // 返回原日期
}

这些运算符重载使得日期对象可以像整数一样进行加减操作,并支持前置和后置的自增自减。

3.3 日期比较运算符重载

通过重载 operator<, operator<=, operator>, operator>=, operator==, operator!=,我们可以比较两个日期对象的大小、相等与否。这里的比较是基于年、月、日逐一进行的。

例如,operator< 通过年、月、日的逐个比较来判断两个日期的先后:

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

4. 输入输出流运算符重载

通过重载输入输出流运算符,用户可以直接用 cincout 进行日期的输入输出。

  • operator<<Date 对象输出为 "年 月 日" 的格式。
  • operator>> 从输入流中读取年、月、日,并进行日期合法性检查。
ostream& operator<<(ostream& out, const Date& d) {
    out << d._year << "年" << d._month << "月" << d._day << "日";
    return out;
}

istream& operator>>(istream& in, Date& d) {
    in >> d._year >> d._month >> d._day;
    if (!d.CheckDate()) {
        cout << "日期非法" << endl;
    }
    return in;
}

测试文件

#define _CRT_SECURE_NO_WARNINGS 1
#include "Date.h"
int main() {
		Date d1, d2;

		// 输入两个日期
		cin >> d1 >> d2;

		// 输出两个日期
		cout << "输入的日期分别为:" << endl;
		cout << d1 << d2;
}

结果

虽然已经很完善了,但也还有优化的空间

5.优化

1. CheckDate() 方法改进

目前的 CheckDate() 方法是一个成员函数,修改的是类的成员变量 _year_month_day。调用时应该注意:

  • 如果 Date 对象已经不合法,则检查时需要输出错误信息,但 Date 构造函数应该尽量避免输出消息,而是通过返回值来告诉调用者是否合法。

解决方式: 在构造函数中调用 CheckDate() 时,输出错误信息,并且返回一个合适的状态或处理方式。

 2. 构造函数中的处理

Date::Date(int year, int month, int day) {
    _year = year;
    _month = month;
    _day = day;
    if (!CheckDate()) {
        cout << "日期非法" << endl;
    }
}

当日期不合法时,只是输出了一条错误消息,而没有采取任何补救措施。更好的方式是可以让构造函数抛出异常,或者修正日期。

解决方式:

  • 使用异常机制,抛出一个日期非法的异常,方便外部调用者捕捉并处理。
  • 另一个方法是让非法日期被调整为一个有效的日期(比如 1900-01-01)。
Date::Date(int year, int month, int day) {
    if (month < 1 || month > 12 || day < 1 || day > GetMonthDay(year, month)) {
        throw invalid_argument("日期非法");
    }
    _year = year;
    _month = month;
    _day = day;
}

3. operator+=operator-= 重载

计算天数时可能会导致多个 while 循环。这个逻辑可以进一步优化,减少重复代码。

例如,在 operator+=operator-= 中,日期变更后的月份检查可以通过 GetMonthDay() 和年份调整来简化。如果需要,可以提取出一个 Normalize() 函数来调整日期和月份。

4. operator- 重载中可能导致逻辑错误

Date Date::operator-(int day) const {
    Date tmp = *this;
    tmp -= day; // 调用 -= 运算符
    return tmp;
}

operator- 会调用 operator-=,但这里的问题是 operator-= 本身是在原地修改日期,而 operator- 是要返回新的日期对象。尽管它返回的是新的 Date 对象,但会修改原来的日期,可能会导致意料之外的行为。

解决方式: 将 operator- 的实现改为独立操作,不依赖 operator-=

Date Date::operator-(int day) const {
    Date tmp = *this;
    tmp._day -= day;  // 不直接修改原对象
    while (tmp._day <= 0) {
        tmp._month--;
        if (tmp._month == 0) {
            tmp._year--;
            tmp._month = 12;
        }
        tmp._day += GetMonthDay(tmp._year, tmp._month);
    }
    return tmp;
}

5. operator++operator--

在前置自增/自减和后置自增/自减的实现中,operator++operator-- 调用的是 operator+=operator-=,这也是合理的。然而,可以通过进一步优化减少重复代码,类似于之前提到的优化方案。

6. 输入输出流重载

  • operator>> 输入错误处理:当日期不合法时,输出错误提示后应该将输入流状态设置为失败,以避免后续操作中使用非法数据。
  • operator<< 输出格式:可以考虑用 std::setwstd::setfill 来确保输出格式的对齐,例如月份和日期为 02 格式。

7. 日期验证的 GetMonthDay 调用效率

每次在增减日期时,都需要调用 GetMonthDay 来获取该月的天数,这样会有一定的性能消耗。可以缓存 GetMonthDay 的结果,或者进行日期验证时,避免重复计算。

大概就这样?

上面的代码没有进行下面所谓的优化因为那是相对于我们来说最方便的写法,而且已经效率很高了不是(