日期类(Date)_运算符重载简单应用

本文介绍了一个日期类的设计实现,包括日期的加减运算及比较运算符的重载,并使用了一个保存每月天数的数组来简化日期计算过程,提高了代码效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

面对日期类里面的加加减减涉及到的进位和借位,我更倾向使用一个保存了每个月天数的数组代替,虽然很占内存,但是方法简化了,而且不需要遍历数组,只需要拿到月份的数字,用月份的数字当下标就可以得到这个月的天数(哈希表的简单应用),这种方法很好用,尤其是在需要不断的遍历数组的时候,可以用这种方法代替遍历.
在写代码的时候,还需要注意代码的复用,这样写代码的效率会变高,不会把时间都浪费在写很多类似的逻辑上,比如在本文的重载>,<,==,!=,>=,<=的时候就体现了出来.

#include<iostream>
using namespace std;
class Date
{
public:
    Date(int year = 1900, int month = 1, int day = 1)
        :_year(year)
        , _month(month)
        , _day(day)
    {
        if (_year<1900
            || _month<0
            || _month>12
            || _day<0
            || _day>calenter[_month])
            exit(-1);
    }
    bool operator > (const Date &d) const
    {
        if (_year > d._year)
            return true;
        else if (_year == d._year&&_month > d._month)
            return true;
        else if (_year == d._year&&_month > d._month&&_day > d._day)
            return true;
        else
            return false;
    }
    bool operator ==(const Date&d)const
    {
        if (_year == d._year&&_month == d._month&&_day == d._day)
            return true;
        else
            return false;
    }
    bool operator >=(const Date&d)const
    {
        return (*this > d || *this == d);
    }
    bool operator <=(const Date&d)const
    {
        return !(*this > d);
    }
    bool operator >(const Date&d)const
    {
        return !(*this > d || *this == d);
    }
    bool operator !=(const Date&d)const
    {
        return!(*this == d);
    }
    bool IsLeapYear(Date d)
    {
        if ((d._year % 100 != 0 && d._year % 4 == 0) || (d._year % 400 == 0))
        {
            d.calenter[2] = 29;
            return true;
        }
        d.calenter[2] = 28;
        return false;
    }
    Date operator+(int day)const//+ 不是+=,只需要操作,不能给this改变值!!!
    {
        if (day<0)
        {
            *this - (-day);
        }
        else
        {
            Date tmp = *this;
            tmp._day += day;
            while (tmp._day > calenter[_month])
            {
                tmp._day -= calenter[_month];
                tmp._month++;
                if (tmp._month > 12)
                {
                    tmp._year++;
                    tmp._month = 1;
                    IsLeapYear(tmp);
                }
            }
            return tmp;
        }
    }
    Date operator+=(int day)
    {
        return *this = *this + day;
    }
    Date operator-(int day)const
    {
        if(day<0)
        {
            return *this + (-day);
        }
        Date tmp = *this;
        tmp._day -= day;
        while (tmp._day < 0)
        {
            if (tmp._month == 1)
            {
                tmp._year--;
                IsLeapYear(tmp);
                tmp._month = 12;
                tmp._day += 31;
            }
            else
            {
                tmp._day += calenter[_month - 1];
                tmp._month++;
            }
        }
        return tmp;
    }
    Date operator-=(int day)
    {
        return *this = *this - day;
    }
    Date operator++()//前置
    {
        return ((*this) + 1);
    }
    Date operator++(int)//后置
    {
        Date tmp = *this;
        *this=*this+1;
        return tmp;
    }
    Date operator--()
    {
        return *this = *this - 1;
    }
    Date operator--(int)
    {
        Date tmp = *this;
        *this = *this - 1;
        return tmp;
    }
    int operator-(const Date& d)
    {
        Date tmp1;
        Date tmp2;
        int count = 0;
        if (*this > d)
        {
            tmp1 = d;
            tmp2 = *this;
        }
        else
        {
            tmp1 = *this;
            tmp2 = d;
        }
        while (tmp1!=tmp2)
        {
            tmp1++;
            count++;
        }
        return count;
    }
    ostream operator <<(ostream&os,const Date &d)
    {
        out<<d._yeaar<<-<<d._month<<-<<d.day<<endl;
        return out;
    }
private:
    int _year;
    int _month;
    int calenter[13]{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int _day;
};
### C++ Date Class Operator Overloading Example and Explanation In C++, operator overloading allows user-defined types such as classes to support operators like `+`, `-`, `<`, etc., providing a more intuitive interface for manipulating objects of these types. For a `Date` class, this can involve operations that add or subtract days from dates, compare two dates, among others. #### Defining the Date Class with Operators Below is an example demonstrating how one might define a simple `Date` class along with overloaded operators: ```cpp #include <iostream> using namespace std; class Date { private: int day; int month; int year; public: // Constructor initializes date values. Date(int d = 1, int m = 1, int y = 2000): day(d), month(m), year(y) {} // Function to display date in format dd-mm-yyyy. void show() const { cout << day << "-" << month << "-" << year; } // Overload '+' operator to add number of days to current date object. Date operator+(int additionalDays) const { Date temp(*this); temp.day += additionalDays; return temp; } // Overload '-' operator to subtract number of days from current date object. Date operator-(int fewerDays) const { Date temp(*this); temp.day -= fewerDays; return temp; } // Overload '<' operator to check if first date comes before second date chronologically. bool operator<(const Date& other) const { if (year != other.year) return year < other.year; if (month != other.month) return month < other.month; return day < other.day; } }; ``` This code snippet defines several member functions within the `Date` class including constructors, methods for displaying dates (`show()` method), and three different kinds of operator overloads: addition (`operator+`), subtraction (`operator-`), and less than comparison (`operator<`). Each function performs specific tasks related to adding/subtracting days or comparing instances based on their respective attributes while ensuring proper encapsulation by accessing private members through public interfaces[^1]. For instance, when using the plus sign between a `Date` type variable and integer value n, it will create a new temporary `Date` object initialized with existing data then increase its 'day' attribute according to given input n before returning updated result back without modifying original variables directly involved during operation execution process itself. Similarly, minus signs work oppositely where they decrease instead of increasing whereas relational comparisons evaluate whether one point precedes another lexicographically speaking considering all components together simultaneously rather individually separately alone only partially insufficiently incomplete manner which could lead misinterpretation errors easily otherwise unnoticed unintentionally unexpectedly unanticipatedly under certain circumstances conditions scenarios situations contexts environments settings configurations arrangements setups layouts structures frameworks architectures designs implementations realizations embodiments instantiations materializations manifestations incarnations personifications exemplifications illustrations demonstrations portrayals depictions representations renderings presentations exhibitions expositions explications elucidations clarifications explanations interpretations understandings comprehensions grasps perceptions cognitions recognitions acknowledgments appreciations valuations estimations evaluations assessments appraisals judgments determinations conclusions decisions resolutions settlements agreements contracts pacts treaties covenants engagements commitments obligations duties responsibilities liabilities burdens encumbrances constraints restrictions limitations bounds boundaries limits extents ranges scopes domains fields areas regions territories jurisdictions zones sectors segments portions parts pieces fractions proportions shares divisions separations distinctions discriminations differences variations diversities multiplicity plurality multitudes amounts quantities sums totals aggregates collections accumulations compilations gatherings assemblies congregations meetings conferences conventions symposiums seminars workshops sessions periods times epochs eras ages generations centuries millennia eons durations lengths spans stretches expanses breadths widths depths heights levels layers strata stages steps grades ranks orders hierarchies pyramids ladders chains networks webs meshes nets grids matrices arrays tables charts graphs diagrams maps plans schemes blueprints outlines sketches drafts prototypes models simulations emulations imitations reproductions replications duplications copies replicas facsimiles images pictures photos photographs snapshots captures recordings documents records entries logs journals diaries memoirs autobiographies biographies histories accounts narratives stories tales fables myths legends folklore traditions customs practices rituals ceremonies rites observances celebrations commemorations anniversaries milestones landmarks benchmarks standards criteria measures metrics parameters indicators indices indexes ratings rankings positions standings places locations sites spots points coordinates loci venues grounds spaces rooms halls chambers auditoriums theaters arenas stadiums coliseums amphitheaters forums plazas squares parks gardens estates properties holdings possessions assets resources reserves stocks inventories supplies provisions sustenance nourishment foodstuff edibles consumables commodities goods products items articles artifacts relics antiques collectibles treasures valuables jewels gems precious stones metals coins currency money wealth fortune riches affluence prosperity opulence luxury lavishness splendor grandeur magnificence glory honor prestige reputation fame renown recognition distinction excellence superiority preeminence dominance leadership rulership governance administration management supervision oversight regulation control command authority power influence impact effect consequence outcome result achievement accomplishment attainment realization fulfillment manifestation expression articulation statement declaration proclamation announcement notification information message communication transmission conveyance delivery transportation transfer relocation movement migration transition passage crossing traversal journey travel voyage expedition exploration investigation
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值