日期类之运算符重载

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(使用前将#替换为@)

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

  • C语言中的递归是如何工作的?

    我试图了解 C 中递归的工作原理 任何人都可以给我解释控制流吗 include
  • 使用 C++ 拆分“[常规设置]”格式的节字符串

    我是 C 新手 我想读取包含部分和键值对的 ini 文件 根据部分 我想读取相应键的值 首先 我想阅读方括号内的部分 请帮忙 谢谢 对于真正的 INI 文件解析 我强烈建议iniparser库 http ndevilla free fr i
  • 宏可以按参数数量重载吗?

    如何this https stackoverflow com q 9183993 153285工作 如何实现 C99 C 11 可变参数宏以仅根据为其提供多少个参数来扩展到不同的事物 编辑 请参阅末尾以获得现成的解决方案 要获得重载的宏 首
  • 无缝滚动瓷砖地图

    我正在开发一个自上而下的角色扮演游戏 并且想要实现无缝滚动地图 也就是说 当玩家探索世界时 地图之间没有加载屏幕 也没有通往下一个区域的 门 我有两种方法可以打破世界 在顶层 我有 区域 它只是 9 个 地图 的集合 这些区域仅由目录表示
  • WinForms - 表单大小错误

    我们有以下代码 private void MainForm Shown object sender EventArgs e RepositionForm private void RepositionForm Rectangle rect
  • 是否有一种算法可以在线性时间内计算数组反转?

    我知道有多少倒转 en wikipedia org wiki Inversion 28discrete mathematics 29 in an n 元素数组可以在 O n log n 操作使用增强型归并排序 http www geeksf
  • Qt QML 数据模型似乎不适用于 C++

    我一直在使用中的示例http doc qt digia com 4 7 qdeclarativemodels html http doc qt digia com 4 7 qdeclarativemodels html这是 QML 声明性数
  • 命名空间“Microsoft”中不存在类型或命名空间名称“Practices”

    我正在使用 Microsoft Visual Studio 2005 for c 我的代码中有以下命名空间 using Microsoft Practices EnterpriseLibrary using Microsoft Practi
  • 捕获另一个进程未处理的异常

    我想知道我是否可以捕获我开始使用 Process Start 的另一个进程抛出的未处理的异常 我知道我可以用这个捕获标准错误link http social msdn microsoft com Forums en US csharpgen
  • 如何强制用户仅使用“new”创建从我派生的类的对象?

    为了实现引用计数 我们使用IUnknown http msdn microsoft com en us library ms680509 VS 85 aspx类接口和智能指针模板类 该接口具有所有引用计数方法的实现 包括Release vo
  • printf() 使用字符串表“解码器环”调试库

    我写这封信是想看看你们中是否有人见过或听说过我即将描述的想法的实现 我有兴趣为嵌入式目标开发 printf 风格的调试库 目标非常遥远 并且我和目标之间的通信带宽预算非常紧张 因此我希望能够以非常有效的格式获取调试消息 通常 调试语句如下所
  • SQL参数化查询不显示结果

    我的 DataAcess 类中有以下函数 但它没有显示任何结果 我的代码如下 public List
  • 该组件没有由 uri 标识的资源

    我想创建一个通用数据网格以在我的所有视图 用户控件上使用 这是我的结构 Class Library called Core Class called ViewBase public class ViewBase UserControl pu
  • EWS - 给予预约,获取预约的所有者副本

    在 EWS 中进行预约后 是否可以获得所有者的副本 例如 如果我登录为user1 我有user1创建的约会的副本user2 我有冒充权 我要编辑user2预约的副本 我怎样才能获得user2 s copy 您可以使用 PidLidClean
  • 从 exit() 和 fork() 返回的结果奇怪地发生了位移

    我有一个 C 代码 有时会自行分叉 每个分叉都会执行一些操作 然后返回一个错误代码 目前 每个子进程返回其 ID 0 n void other int numero exit numero int main for int i 0 i lt
  • 为什么调试器只显示数组指针中的一个元素?

    首先 我知道new是执行此操作的 C 方法 我只是表明有不止一种方法可以重现此错误 而且两种方法都令人难以置信的令人沮丧 我有两种形式的源文件 我正在尝试调试另一个编程作业 但我并没有寻求帮助 基本上 我正在尝试重新实施set作为一个类 具
  • 获取会议组织者邮件地址 EWS API

    我想使用 EWS API 获取会议组织者的邮件地址 目前 我刚刚获得约会项目的一些属性 我听说你可以设置你想要获取哪些属性 我的代码看起来像这样 CalendarView cview new CalendarView start end c
  • 扔掉挥发物安全吗?

    大多数时候 我都是这样做的 class a public a i 100 OK delete int j Compiler happy But is it safe The following code will lead compilat
  • 从 STL 列表中删除项目

    我想创建一个函数 如果符合特定条件 则将项目从一个 STL 列表移动到另一个列表 这段代码不是这样做的方法 迭代器很可能会被擦除 函数失效并导致问题 for std list
  • C# amo 获取角色完整

    我正在开发一个 SSAS 项目 其中除其他事项外 我需要获取 C 中表格多维数据集的完整用户列表 目前我让它以这样的方式工作 我可以获得角色 但数据不完整 当我调用 Server Database Roles 为了便于阅读而简化 属性并枚举

随机推荐

  • 招募 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