日期类之运算符重载

2023-11-17

①date.h

#pragma once 

#include <iostream>
#include <assert.h>

using namespace std;

class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
        :_year(year)
        , _month(month)
        , _day(day)
    {
        if (!IsInvalid())
        {
            assert(false);
        }
    }

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

    ~Date(){}

    bool IsInvalid();
    void Show();

    Date& 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 < d2
    bool operator>(const Date& d);      //>重载
    // d1 > d2 
    bool operator<(const Date& d);      //<重载

    // d1 + 10 
    Date operator+(int day);            //+重载
    Date& operator+=(int day);      //+=重载

    Date operator-(int day);            //-重载
    Date& operator-=(int day);      //-=重载

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

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

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

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

②date.cpp

#include "date.h"

void Date::Show()
{
    cout << _year << "-" << _month << "-" << _day << endl;
}

bool IsLeapYear(int year)
{
    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
    {
        return true;
    }
    return false;
}

int GetMonthDay(int year, int month)
{
    int array[] = { -1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int day = array[month];
    if (month == 2 && IsLeapYear(year))
    {
        day = 29;
    }
    return day;
}

bool Date::IsInvalid()
{
    return _year >= 0
        && _month >= 0 && _month <= 12
        && _day > 0 && _day <= GetMonthDay(_year, _month);
}

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


bool Date::operator==(const Date& d)        //隐含的this指针
{
    return this->_year == d._year
        && this->_month == d._month
        && this->_day == d._day;
}

bool Date::operator!=(const Date& d)
{
    return this->_year != d._year
        || this->_month != d._month
        || this->_day != d._day;
}

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

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)
{
    if ((_year > d._year)
        || (_year == d._year && _month > d._month)
        || (_year == d._year && _month == d._month && _day > d._day))
    {
        return true;
    }
    return false;
}


Date Date::operator+(int day)       //本身并没有改变,不能返回引用
{
    Date ret(*this);
    ret._day += day;
    while (ret._day > GetMonthDay(ret._year, ret._month))
    {
        int monthday = GetMonthDay(ret._year, ret._month);
        ret._day -= monthday;
        ret._month++;
        if (ret._month > 12)
        {
            ret._month = 1;
            ret._year++;
        }
    }
    return ret;
}

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

Date Date::operator-(int day)
{
    if (day < 0)
    {
        return *this + (-day);
    }
    Date ret(*this);
    ret._day -= day;
    while (ret._day < 0)
    {
        if (ret._month == 1)
        {
            ret._month = 12;
            ret._year--;
        }
        else
        {
            ret._month--;
        }
        int monthday = GetMonthDay(ret._year, ret._month);
        ret._day += monthday;
    }
    return ret;
}

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

Date& Date::operator++() // 前置(效率高)
{
    *this += 1;
    return *this;
}

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

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


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

int Date::operator-(const Date& d)      //计算两个日期相差天数
{
    //先确定哪个日期小,然后将小的往大的加,知道两个日期相等,就得到相差天数
    int flag = 1;
    Date max(*this);
    Date min(d);
    if (*this < d)
    {
        min = *this;
        max = d;
        flag = -1;
    }
    int days = 0;
    while (min < max)
    {
        min++;
        days++;
    }
    return days * flag;
}



int main()
{
    Date d1(2018, 3, 26);
    d1.Show();
    Date d2(2018, 4, 25);
    d2 = d1;
    d2.Show();

    cout << "测试重载==:" << d1.operator==(d2) << endl;

    cout << "测试重载!=:" << d1.operator!=(d2) << endl;

    cout << "测试重载>:" << d1.operator>(d2) << endl;

    cout << "测试重载<:" << d1.operator<(d2) << endl;

    cout << "测试重载>=:" << d1.operator>=(d2) << endl;

    cout << "测试重载<=:" << d1.operator<=(d2) << endl;

    Date d3 = d2.operator+(10);
    d3.Show();

    d2.operator+=(20);
    d2.Show();

    Date d4 = d2.operator-(-30);
    d4.Show();

    d2.operator-=(30);
    d2.Show();

    Date d5 = d2++;
    d5.Show();

    ++d2;
    d2.Show();

    --d2;
    d2.Show();

    Date d6 = d2--;
    d6.Show();

    Date d(2018, 3, 27);
    Date d7(2018, 9, 10);
    d.Show();
    d7.Show();
    int days = d7 - d;
    cout << " 相差天数:" << days << endl;

    system("pause");
    return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

日期类之运算符重载 的相关文章

  • 静态只读字符串数组

    我在我的 Web 应用程序中使用静态只读字符串数组 基本上数组有错误代码 我将所有类似的错误代码保存在一个数组中并检查该数组 而不是检查不同常量字符串中的每个错误代码 like public static readonly string m
  • 如何从 C# 中的 dataTable.Select( ) 查询中删除单引号?

    所以我有一个经销商名称列表 我正在我的数据表中搜索它们 问题是 一些傻瓜必须被命名为 Young s 这会导致错误 drs dtDealers Select DealerName dealerName 所以我尝试替换字符串 尽管它对我不起作
  • 使用 C# 登录《我的世界》

    我正在尝试为自己和一些朋友创建一个简单的自定义 Minecraft 启动器 我不需要启动 Minecraft 的代码 只需要登录的实际代码行 例如 据我所知 您过去可以使用 string netResponse httpGET https
  • 如何在多线程C++ 17程序中交换两个指针?

    我有两个指针 pA 和 pB 它们指向两个大的哈希映射对象 当pB指向的哈希图完全更新后 我想交换pB和pA 在C 17中 如何快速且线程安全地交换它们 原子 我是 c 17 的新手 2个指针的原子无等待交换可以通过以下方式实现 inclu
  • 如何捕获未发送到 stdout 的命令行文本?

    我在项目中使用 LAME 命令行 mp3 编码器 我希望能够看到某人正在使用什么版本 如果我只执行 LAME exe 而不带参数 我会得到 例如 C LAME gt LAME exe LAME 32 bits version 3 98 2
  • 如何判断计算机是否已重新启动?

    我曾经使用过一个命令行 SMTP 邮件程序 作为试用版的限制 它允许您在每个 Windows 会话中最多接收 10 封电子邮件 如果您重新启动计算机 您可能还会收到 10 个以上 我认为这种共享软件破坏非常巧妙 我想在我的应用程序中复制它
  • 如何使用 Castle Windsor 将对象注入到 WCF IErrorHandler 实现中?

    我正在使用 WCF 开发一组服务 该应用程序正在使用 Castle Windsor 进行依赖注入 我添加了一个IErrorHandler通过属性添加到服务的实现 到目前为止一切正常 这IErrorHandler对象 一个名为FaultHan
  • 为什么在 WebApi 上下文中在 using 块中使用 HttpClient 是错误的?

    那么 问题是为什么在 using 块中使用 HttpClient 是错误的 但在 WebApi 上下文中呢 我一直在读这篇文章不要阻止异步代码 https blog stephencleary com 2012 07 dont block
  • C# 数据表更新多行

    我如何使用数据表进行多次更新 我找到了这个更新 1 行 http support microsoft com kb 307587 my code public void ExportCSV string SQLSyntax string L
  • File.AppendText 尝试写入错误的位置

    我有一个 C 控制台应用程序 它作为 Windows 任务计划程序中的计划任务运行 此控制台应用程序写入日志文件 该日志文件在调试模式下运行时会创建并写入应用程序文件夹本身内的文件 但是 当它在任务计划程序中运行时 它会抛出一个错误 指出访
  • 告诉 Nancy 将枚举序列化为字符串

    Nancy 默认情况下在生成 JSON 响应时将枚举序列化为整数 我需要将枚举序列化为字符串 有一种方法可以通过创建来自定义 Nancy 的 JSON 序列化JavaScript 原始转换器 https github com NancyFx
  • 将 Long 转换为 DateTime 从 C# 日期到 Java 日期

    我一直尝试用Java读取二进制文件 而二进制文件是用C 编写的 其中一些数据包含日期时间数据 当 DateTime 数据写入文件 以二进制形式 时 它使用DateTime ToBinary on C 为了读取 DateTime 数据 它将首
  • C# 存档中的文件列表

    我正在创建一个 FileFinder 类 您可以在其中进行如下搜索 var fileFinder new FileFinder new string C MyFolder1 C MyFolder2 new string
  • 打破 ReadFile() 阻塞 - 命名管道 (Windows API)

    为了简化 这是一种命名管道服务器正在等待命名管道客户端写入管道的情况 使用 WriteFile 阻塞的 Windows API 是 ReadFile 服务器已创建启用阻塞的同步管道 无重叠 I O 客户端已连接 现在服务器正在等待一些数据
  • 使用valgrind进行GDB远程调试

    如果我使用远程调试gdb我连接到gdbserver using target remote host 2345 如果我使用 valgrind 和 gdb 调试内存错误 以中断无效内存访问 我会使用 target remote vgdb 启动
  • 在视口中查找 WPF 控件

    Updated 这可能是一个简单或复杂的问题 但在 wpf 中 我有一个列表框 我用一个填充数据模板从列表中 有没有办法找出特定的数据模板项位于视口中 即我已滚动到其位置并且可以查看 目前我连接到了 listbox ScrollChange
  • 为什么这个二维指针表示法有效,而另一个则无效[重复]

    这个问题在这里已经有答案了 这里我编写了一段代码来打印 3x3 矩阵的对角线值之和 这里我必须将矩阵传递给函数 矩阵被传递给指针数组 代码可以工作 但问题是我必须编写参数的方式如下 int mat 3 以下导致程序崩溃 int mat 3
  • String.Empty 与 "" [重复]

    这个问题在这里已经有答案了 可能的重复 String Empty 和 有什么区别 https stackoverflow com questions 151472 what is the difference between string
  • 使用 omp_set_num_threads() 将线程数设置为 2,但 omp_get_num_threads() 返回 1

    我有以下使用 OpenMP 的 C C 代码 int nProcessors omp get max threads if argv 4 NULL printf argv 4 s n argv 4 nProcessors atoi argv
  • 如何将十六进制字符串转换为无符号长整型?

    我有以下十六进制值 CString str str T FFF000 如何将其转换为unsigned long 您可以使用strtol作用于常规 C 字符串的函数 它使用指定的基数将字符串转换为 long long l strtol str

随机推荐

  • 招募 AIGC 训练营助教 @上海

    诚挚邀请对社区活动感兴趣的你 成为我们近期开展的训练营助教 与我们共同开启这场创新之旅 助教需要参与 协助策划和组织训练营活动 协助招募和筛选学员 协助制定训练营的宣传方案 负责协调和组织各项活动 助教可获得 AIGC知识库 获得社区提供的
  • 服务器端Session、客户端Session和Cookie的区别

    1 Session其实分为客户端Session和服务器端Session 当用户首次与Web服务器建立连接的时候 服务器会给用户分发一个 SessionID作为标识 SessionID是一个由24个字符组成的随机字符串 用户每次提交页面 浏览
  • 微型小程序页面跳转加携带数据

    一 WXML中
  • 列表数据转树形数据 trees-plus 使用方法(支持typescript)

    trees plus Operations related to tree data Install npm i trees plus S Import import TreesPlus from trees plus Usage impo
  • 如何使用DLL函数动态加载-静态加载

    公司里的项目里用到加密解密 使用的是客户指定的DLL库来加密解密 开始 我按照以前的方法来使用DLL库 这里也介绍下吧 虽然网上很多 一般动态加载DLL的步骤如下 HINSTANCE DLL库实例名 LoadLibrary T DLL库名
  • 高德api 实现根据中文地址地图打点弹窗

  • diffusion models笔记

    ELBO of VDM Understanding 1 中讲 variational diffusion models VDM 的 evidence lower bound ELBO 推导时 53 式有一个容易引起误会的记号
  • Promethus(普罗米修斯)安装与配置(亲测可用)

    1 普罗米修斯概述 Prometheus 是由go语言 golang 开发 是一套开源的监控 报警 时间序列数 据库的组合 适合监控docker容器 Prometheus是最初在SoundCloud上构建的开源系统监视和警报工具包 自201
  • 字符串匹配算法0-基本概念

    字符串匹配的算法在很多领域都有重要的应用 这就不多说了 我们考虑一下算法的基本的描述 给定大小为 字母表 上的长度为n的文本t和长度为m的模式p 找出t中所有的p的出现的地方 一个长度为m的串p表示为一个数组p 0 m 1 这里m 0 当然
  • [前端系列第5弹]JQuery简明教程:轻松掌握Web页面的动态效果

    在这篇文章中 我将介绍jQuery的基本概念 语法 选择器 方法 事件和插件 以及如何使用它们来实现Web页面的动态效果 还将给一些简单而实用的例子 让你可以跟着我一步一步地编写自己的jQuery代码 一 什么是JQuery JQuery是
  • 【异步系列五】关于async/await与promise执行顺序详细解析及原理详解

    前段时间总结了几篇关于异步原理 Promise原理 Promise面试题 async await 原理的文章 链接如下 感兴趣的可以去看下 相信会有所收获 一篇文章理清JavaScript中的异步操作原理 Promise原理及执行顺序详解
  • 博客4:YOLOv5车牌识别实战教程:模型优化与部署

    摘要 本篇博客将详细介绍如何对YOLOv5车牌识别模型进行优化和部署 我们将讨论模型优化策略 如模型蒸馏 模型剪枝和量化等 此外 我们还将介绍如何将优化后的模型部署到不同平台 如Web 移动端和嵌入式设备等 车牌识别视频 正文 4 1 模型
  • 4.5 静态库链接

    4 5 静态库链接 一种语言的开发环境往往会附带语言库 language library 这些库通常是对操作系统API的包装 例如C语言标准库的函数strlen 并没有调用任何操作系统的API 但是很大一部分库函数都要调用操作系统API 例
  • 三目运算符优先级

    今天发表一个遇到的js的三元运算符优先级问题 如图 在解答这一题的时候 首先我们先理解什么是三元运算符 如名字一样是有三个操作数 语法 条件判断 结果1 结果2 如果条件成立 则返回结果1 否则返回结果2 在这里 三元运算符优先级是最低的
  • C语言实现TCP连接

    开发环境 TCP服务端 TCP UDP测试工具 开发环境 Linux 编程语言 C语言 TCP UDP测试工具工具的使用请自行百度 我们用这款软件模拟TCP服务端 效果展示 代码编写 include
  • bootstrap中container类和container-fluid类的区别

    近几天才开始系统的学习bootstrap 但马上就遇到了一个 拦路虎 container和container fluid到底什么区别 查了很多资料 看到很多人和我有同样的疑问 但是下面的回答一般都是一个是响应式一个宽度是百分百 说的好像是那
  • 【华为OD机试】斗地主之顺子(C++ Python Java)2023 B卷

    时间限制 C C 1秒 其他语言 2秒 空间限制 C C 262144K 其他语言524288K 64bit IO Format lld 语言限定 C clang11 C clang 11 Pascal fpc 3 0 2 Java jav
  • firefox 阻止此页面创建其他对话框的解决方法

    用Firefox操作弹出界面时总是遇到 firefox 阻止此页面创建其他对话框 点击确定后 控制台就会报错误 解决方法 1 在firefox里输入about config 2 在列表框里右键 gt 新建 gt 整数 3 输入选项名dom
  • Redis底层数据结构

    Redis简单介绍一下 Redis是一个开源的 使用C语言编写的 支持网络交互的 可基于内存也可持久化的Key Value数据库 有哪些数据结构 说起Redis数据结构 肯定先想到Redis的5 种基本数据结构 String 字符串 Lis
  • 日期类之运算符重载

    date h pragma once include