C++之运算符重载的实例(日期类实现方式)

 更新时间:2025年06月03日 10:09:37   作者:zzh_zao  
这篇文章主要介绍了C++之运算符重载的实例(日期类实现方式),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

C++日期类的实现与深度解析

在C++编程中,自定义数据类型是构建复杂应用的基础。日期作为一个常用的数据类型,涉及到多种操作,如日期的加减、比较、计算间隔天数等。

一、代码结构概览

我们实现的Date类包含了日期相关的核心功能,代码分为头文件Date.h和源文件Date.cpp两部分。

头文件负责类的声明,定义类的成员函数接口和数据成员;源文件则实现这些成员函数,完成具体的业务逻辑。

1.1 头文件 Date.h

// Date.h
#pragma once
#include <iostream>
#include <assert.h>
using namespace std;

class Date
{
public:
    // 获取某年某月的天数
    int GetMonthDay(int year, int month) const;
    // 全缺省的构造函数
    Date(int year = 1900, int month = 1, int day = 1);
    // 拷贝构造函数
    Date(const Date& d);
    // 赋值运算符重载
    Date& operator=(const Date& d);
    // 析构函数
    ~Date();
    // 日期+=天数
    Date& operator+=(int day);
    // 日期+天数
    Date operator+(int day) const;
    // 日期-天数
    Date operator-(int day) const;
    // 日期-=天数
    Date& operator-=(int day);
    // 前置++
    Date& operator++();
    // 后置++
    Date operator++(int);
    // 后置--
    Date operator--(int);
    // 前置--
    Date& operator--();
    // >运算符重载
    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;
    // 日期-日期 返回天数
    int operator-(const Date& d) const;
    
    // 输出日期
    void Print() const;

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

头文件中定义了Date类,包含私有成员变量_year_month_day,用于存储日期的年、月、日信息;同时声明了一系列成员函数,涵盖日期计算、比较、赋值等操作。

1.2 源文件 Date.cpp

// Date.cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include "Date.h"

// 实现获取某年某月天数的函数
int Date::GetMonthDay(int year, int month) const
{
    assert(month > 0 && month < 13);
    static int arr[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;
    return arr[month];
}

// 全缺省构造函数,同时检查日期合法性
Date::Date(int year, int month, int day)
{
    // 检查日期合法性
    if (year < 0 || month < 1 || month > 12 || day < 1 || day > GetMonthDay(year, month))
    {
        cout << "Invalid date: " << year << "-" << month << "-" << day << endl;
        // 使用默认值
        _year = 1900;
        _month = 1;
        _day = 1;
    }
    else
    {
        _year = year;
        _month = month;
        _day = day;
    }
}

// 拷贝构造函数
Date::Date(const Date& d)
{
    _year = d._year;
    _month = d._month;
    _day = d._day;
}

// 赋值运算符重载
Date& Date::operator=(const Date& d)
{
    if (this != &d)
    {
        _year = d._year;
        _month = d._month;
        _day = d._day;
    }
    return *this;
}

// 析构函数,无需显式将成员置零
Date::~Date()
{
    // 不需要在这里将成员置零
}

// 日期加上指定天数
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)
        {
            _month = 1;
            _year++;
        }
    }
    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;
}

// 前置++操作
Date& Date::operator++()
{
    *this += 1;
    return *this;
}

// 后置++操作
Date Date::operator++(int)
{
    Date tmp(*this);
    *this += 1;
    return tmp;
}

// 后置--操作
Date Date::operator--(int)
{
    Date tmp(*this);
    *this -= 1;
    return tmp;
}

// 前置--操作
Date& Date::operator--()
{
    *this -= 1;
    return *this;
}

// 比较两个日期大小
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 _year == d._year && _month == d._month && _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 !(*this == d);
}

// 计算两个日期之间的天数差
int Date::operator-(const Date& d) const
{
    Date min = *this;
    Date max = d;
    int flag = 1;
    
    if (min > max)
    {
        min = d;
        max = *this;
        flag = -1;
    }
    
    int days = 0;
    
    // 优化算法:逐月计算天数差
    while (min < max)
    {
        // 计算下个月1号的日期
        Date nextMonth(min._year, min._month + 1, 1);
        if (nextMonth > max)
        {
            // 如果下个月超过了max,则直接计算当前月剩余天数
            days += max._day - min._day;
            break;
        }
        else
        {
            // 计算当前月的剩余天数
            days += GetMonthDay(min._year, min._month) - min._day + 1;
            // 跳到下个月1号
            min = nextMonth;
        }
    }
    
    return days * flag;
}

// 输出日期
void Date::Print() const
{
    cout << _year << "-" << _month << "-" << _day << endl;
}

源文件中具体实现了头文件声明的各个成员函数,从基础的日期创建、拷贝、赋值,到复杂的日期计算与比较,每个函数各司其职,共同完成日期类的功能。

二、关键函数实现解析

2.1 获取某月天数函数 GetMonthDay

int Date::GetMonthDay(int year, int month) const
{
    assert(month > 0 && month < 13);
    static int arr[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;
    return arr[month];
}

该函数用于获取指定年份和月份的天数。通过一个静态数组arr存储常规月份的天数,并根据闰年规则(能被4整除但不能被100整除,或者能被400整除)判断2月的天数。

函数声明为const成员函数,表明不会修改对象的状态,也允许常量对象调用。

2.2 构造函数 Date

Date::Date(int year, int month, int day)
{
    // 检查日期合法性
    if (year < 0 || month < 1 || month > 12 || day < 1 || day > GetMonthDay(year, month))
    {
        cout << "Invalid date: " << year << "-" << month << "-" << day << endl;
        // 使用默认值
        _year = 1900;
        _month = 1;
        _day = 1;
    }
    else
    {
        _year = year;
        _month = month;
        _day = day;
    }
}

构造函数用于初始化Date对象。在初始化前,对传入的年份、月份和日期进行合法性检查,若日期不合法,则将对象初始化为默认日期1900-01-01,保证对象的有效性。

2.3 日期加减法运算

在这里为了减少类类型的拷贝,节约资源,通常先实现+= 或 -=;

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)
        {
            _month = 1;
            _year++;
        }
    }
    return *this;
}

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

operator+=函数实现了日期加上指定天数的功能,通过循环处理跨月、跨年的情况;operator+函数则基于operator+=,返回一个新的日期对象,保持原对象不变。

类似地,operator-=operator-函数实现了日期减法操作。

2.4 前置与后置自增/自减操作

为区分前置与后置,后置类型要在括号当中加入int形参,与前置构成重载;

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

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

前置自增operator++先对日期进行加1操作,再返回修改后的对象;后置自增operator++(int)通过创建临时对象保存原始状态,对原对象进行加1操作后,返回临时对象,保证后置自增“先使用,后修改”的语义。自减操作operator--operator--(int)的实现原理与之类似。

2.5 日期比较与差值计算

在自我实现日期比较时,只需实现一个>或<,加上一个=,其余的都可以用这两个来实现。

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

int Date::operator-(const Date& d) const
{
    Date min = *this;
    Date max = d;
    int flag = 1;
    
    if (min > max)
    {
        min = d;
        max = *this;
        flag = -1;
    }
    
    int days = 0;
    
    // 优化算法:逐月计算天数差
    while (min < max)
    {
        // 计算下个月1号的日期
        Date nextMonth(min._year, min._month + 1, 1);
        if (nextMonth > max)
        {
            // 如果下个月超过了max,则直接计算当前月剩余天数
            days += max._day - min._day;
            break;
        }
        else
        {
            // 计算当前月的剩余天数
            days += GetMonthDay(min._year, min._month) - min._day + 1;
            // 跳到下个月1号
            min = nextMonth;
        }
    }
    
    return days * flag;
}

日期比较函数通过依次比较年份、月份和日期,判断两个日期的大小关系;operator-函数用于计算两个日期之间的天数差,采用逐月计算的优化算法,减少不必要的循环次数,提高计算效率。

三、代码优化与注意事项

3.1 代码优化

  1. 成员函数添加const修饰:将不修改对象状态的成员函数声明为const,如GetMonthDay、日期比较函数等,提高代码的安全性和可读性,同时允许常量对象调用这些函数。
  2. 日期差值计算优化:在计算两个日期差值时,采用逐月计算的方式,避免了每次只增加一天的低效循环,大幅提升计算效率。

3.2 注意事项

  1. 日期合法性检查:在构造函数和其他涉及日期修改的函数中,要确保对日期的合法性进行严格检查,防止出现无效日期。
  2. 运算符重载的一致性:在重载日期相关运算符时,要保证逻辑的一致性和正确性,例如operator+operator+=之间的关系,避免出现逻辑矛盾。
  3. 避免内存泄漏:虽然Date类中没有动态内存分配,但在更复杂的类设计中,析构函数要正确释放资源,防止内存泄漏。

四、总结

通过实现Date类,运用了C++中类的设计、运算符重载、构造函数、析构函数等核心概念。日期类的实现不仅涉及到基本的数学计算,还需要处理各种边界情况和逻辑判断。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • C++ JSON库nlohmann指南

    C++ JSON库nlohmann指南

    本文详细介绍了C++中流行的JSON库nlohmann的功能与使用方法,包括声明与构造JSON对象、数组,解析与序列化JSON数据,以及如何进行元素的获取、修改、删除等常见操作,感兴趣的朋友跟随小编一起看看吧
    2025-10-10
  • 基于c++ ege图形库实现五子棋游戏

    基于c++ ege图形库实现五子棋游戏

    这篇文章主要为大家详细介绍了基于c++ ege图形库实现五子棋游戏,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-12-12
  • C++ 手撸简易服务器

    C++ 手撸简易服务器

    本文主要介绍了C++ 手撸简易服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-03-03
  • C++实现LeetCode(74.搜索一个二维矩阵)

    C++实现LeetCode(74.搜索一个二维矩阵)

    这篇文章主要介绍了C++实现LeetCode(74.搜索一个二维矩阵),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-07-07
  • C++实例分析组合数的计算与排列组合的产生

    C++实例分析组合数的计算与排列组合的产生

    这篇文章主要介绍了C++组合数的计算与排列和组合无重集元素的产生,对计算算法感兴趣的同学,可以参考一下,理解其原理,并且试验一下。
    2022-07-07
  • 深入理解C语言中指针常量和常量指针

    深入理解C语言中指针常量和常量指针

    本文介绍了C语言中的指针常量和常量指针,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-12-12
  • C++之关于string对象的大小比较

    C++之关于string对象的大小比较

    这篇文章主要介绍了C++之关于string对象的大小比较方式,具有很好的 参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-11-11
  • C++用read()和write()读写二进制文件的超详细教程

    C++用read()和write()读写二进制文件的超详细教程

    二进制的文件肉眼我们是读不懂的,如果通过二进制的读写操作就可以读懂,下面这篇文章主要给大家介绍了关于C++用read()和write()读写二进制文件的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-06-06
  • C语言详细分析不同类型数据在内存中的存储

    C语言详细分析不同类型数据在内存中的存储

    使用编程语言进行编程时,需要用到各种变量来存储各种信息。变量保留的是它所存储的值的内存位置。这意味着,当您创建一个变量时,就会在内存中保留一些空间。您可能需要存储各种数据类型的信息,操作系统会根据变量的数据类型,来分配内存和决定在保留内存中存储什么
    2022-08-08
  • C++中对象的常引用、动态建立和释放相关知识讲解

    C++中对象的常引用、动态建立和释放相关知识讲解

    这篇文章主要介绍了C++中对象的常引用、动态建立和释放相关知识讲解,是C++入门学习中的基础知识,需要的朋友可以参考下
    2015-09-09

最新评论