[C.C++] C++实现日期类的示例详解

1845 0
王子 2023-2-25 16:44:20 | 显示全部楼层 |阅读模式
目录

    一、获取某年某月的天数二、Date的默认成员函数(全缺省的默认构造)三、运算符重载
      1.+ =、+、- =、-2.==、!=、>、>=、<、<=3.前置++、–、后置++、–4.<<流插入、>>流提取(内联的<<、>>重载函数)
    四、两个日期相减,返回天数五、日期类完整代码
      1.Date.h2.Date.cpp3.Test.cpp



一、获取某年某月的天数

1.在实现日期类的过程中,日期加减天数的应用场景一定会频繁使用到这个函数接口,因为加减天数会使得月份发生变化,可能增月或减月,这个时候就需要在day上面扣除或增加当年当月的天数,所以这个接口非常的重要。
2.为了方便获取到某年某月的天数,我们将数组大小设置为13,以便月份能够和数组中的下标对应上,并且我们将数组设置为静态,就不需要考虑每次调用函数建立栈帧后重新给数组分配空间的事情了,因为数组一直被存放在静态区。
3.四年一闰,百年不闰,四百年一闰,闰年或平年会影响2月份的天数,所以我们要将这种情况单拉出来进行处理分析。
int GetMonthDay(int year, int month)
    {
        static int monthDayArray[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;
        }
        else
        {
            return monthDayArray[month];
        }
    }

二、Date的默认成员函数(全缺省的默认构造)

1.编译器默认生成的构造函数不会处理内置类型,所以我们需要自己去写构造函数,非常推荐大家使用全缺省的构造函数,编译器对自定义类型会自动调用该类类型的默认构造。
2.由于Date类的成员变量都是内置类型,所以析构函数不需要我们自己写,因为没有资源的申请。并且拷贝构造和赋值重载也不需要写,因为Date类不涉及深拷贝的问题,仅仅使用浅拷贝就够了。
3.至于取地址重载和const对象取地址重载,本身就不需要我们写。
除非你不想让别人通过取地址符号&来拿到实例化对象的地址,那可以返回nullptr,来屏蔽别人通过&拿到对象地址,但极大概率没人这么做。
Date(int year = 1, int month = 1, int day = 1)
        {
                _year = year;
                _month = month;
                _day = day;

                // 检查日期是否合法
                if (!(year >= 1&& (month >= 1 && month <= 12)&& (day >= 1 && day <= GetMonthDay(year, month))))
                {
                        cout << "非法日期" << endl;
                }
        }

三、运算符重载


1.+ =、+、- =、-

1.实现+ =或 - =之后,就不需要实现+ -的重载了,我们可以调用之前实现过的成员函数,需要注意的是形参day有可能是负数,对于这种情况可以将其交给+=或-=对方来处理这种情况,因为这两个运算符正好是反过来的,可以处理对方day为负数的时候的情况。
2.+=实现的思路就是,实现一个循环,直到天数回到该月的正常天数为止,在循环内部要做的就是进月和进年,让天数不断减去本月天数,直到恢复本月正常天数时,循环结束,返回对象本身即可。
3.-=实现的思路就是,实现一个循环,直到天数变为正数为止,在循环内部要做的就是借月和借年,让天数不断加上上一个月份的天数,直到恢复正数为止,循环结束,返回对象本身。
Date& Date::operator+=(int day)
{
        if (day < 0)
        {
                return *this -= abs(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)
{
        Date ret(*this);
        ret += day;
        return ret;
}

Date& Date::operator-=(int day)
{
        if (day < 0)
        {
                return *this += abs(day);
        }

        _day -= day;
        while (_day <= 0)
        {
                --_month;
                if (_month == 0)
                {
                        _month = 12;
                        --_year;
                }
                _day += GetMonthDay(_year, _month);

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

2.==、!=、>、>=、<、<=

1.下面这些比较运算符的重载应该是非常简单的了,只需要实现一半的运算符重载即可,剩余运算符利用反逻辑操作符!即可轻松实现。
bool Date::operator==(const Date& d)const
{
        return _year == d._year && _month == d._month && _day == d._day;
}

bool Date::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;
        }

        return false;
}

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

3.前置++、–、后置++、–

1.实现前置和后置的区别就是,一个返回临时对象,一个返回对象本身,在实现+=和-=以及+ -这些运算符重载之后,自增或自减运算符的重载非常简单了,也是直接套用即可。
Date& Date::operator++()
{
        return *this += 1;
}
Date Date::operator++(int)
{
        Date ret(*this);
        *this += 1;
        return ret;
}

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

        *this -= 1;

        return ret;
}

4.<<流插入、>>流提取(内联的<<、>>重载函数)

1.流插入和流提取不适用于在类内部实现,因为隐含的this指针会先抢到第一个参数位置,而我们又习惯将cout作为左操作数使用,这就产生了冲突,所以我们需要将重载放到全局位置,并且我们很可能频繁使用这两个重载,所以最好搞成内联函数。
2.起始流插入和流提取的重载非常简单,本质上就是利用了库中实现的类的实例化对象cin和cout,他们完全支持输出编译器的内置类型,而所有的自定义类型实际上都是内置类型堆砌而成,我们只需要在重载中将对象的内置类型一个个的输出即可,这就是对象的流插入和流提取的本质思想。


inline ostream& operator<<(ostream& out, const Date& d)
{
    out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
    return out;
}
inline istream& operator>>(istream& in,  Date& d)
{
    in >> d._year >> d._month >> d._day;
    return in;
}

四、两个日期相减,返回天数

1.这个模块的实现非常的有意思,利用了一个编程技巧假设,我们不知道哪个对象的日期更大一些,那我们就先假设一下,如果判断错误,只要纠正一下即可。
然后定义一个计数器,让较小日期自增,直到和较大日期相等为止,最后的计数器就是日期之间相差的天数,这个天数既有可能是正,也有可能是负,所以这里利用了flag标志位,返回flag和cnt的乘积。
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 cnt = 0;
        while (min != max)
        {
                ++min;
                ++cnt;
        }
        return cnt * flag;
}

五、日期类完整代码


1.Date.h

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

class Date
{
public:
        friend ostream& operator<<(ostream& out, const Date& d);
        friend istream& operator>>(istream& in,  Date& d);

        int GetMonthDay(int year, int month)
        {
                //静态数组,每次调用不用频繁在栈区创建数组
                static int monthDayArray[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;
                }
                else
                {
                        return monthDayArray[month];
                }
        }
        Date(int year = 1, int month = 1, int day = 1)
        {
                _year = year;
                _month = month;
                _day = day;

                // 检查日期是否合法
                if (!(year >= 1&& (month >= 1 && month <= 12)&& (day >= 1 && day <= GetMonthDay(year, month))))
                {
                        cout << "非法日期" << endl;
                }
        }
        //拷贝构造、赋值重载、析构函数都不用自己写

        void Print()const
        {
                cout << _year << "年" << _month << "月" << _day << "日" << endl;
        }

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

        Date& operator-=(int day);
        Date operator-(int day);

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

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

        // d1 - d2;
        int operator-(const Date& d)const;

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

inline ostream& operator<<(ostream& out, const Date& d)
{
        out << d._year << "年" << d._month << "月" << d._day << "日" << endl;
        return out;
}
inline istream& operator>>(istream& in,  Date& d)
{
        in >> d._year >> d._month >> d._day;
        return in;
}

2.Date.cpp

#include "Date.h"

bool Date::operator==(const Date& d)const
{
        return _year == d._year && _month == d._month && _day == d._day;
}

bool Date::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;
        }

        return false;
}

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

Date& Date::operator+=(int day)
{
        if (day < 0)
        {
                return *this -= abs(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)
{
        Date ret(*this);
        ret += day;
        return ret;
}

Date& Date::operator-=(int day)
{
        if (day < 0)
        {
                return *this += abs(day);
        }

        _day -= day;
        while (_day <= 0)
        {
                --_month;
                if (_month == 0)
                {
                        _month = 12;
                        --_year;
                }
                _day += GetMonthDay(_year, _month);

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

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

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

        *this -= 1;

        return ret;
}

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 cnt = 0;
        while (min != max)
        {
                ++min;
                ++cnt;
        }
        return cnt * flag;
}

3.Test.cpp

#include "Date.h"

void TestDate1()
{
        Date d1(2022, 10, 8);
        Date d3(d1);
        Date d4(d1);

        d1 -= 10000;
        d1.Print();

        Date d2(d1);
        /*Date d3 = d2 - 10000;
        d3.Print();*/
        (d2 - 10000).Print();
        d2.Print();

        d3 -= -10000;
        d3.Print();

        d4 += -10000;
        d4.Print();
}

void TestDate2()
{
        Date d1(2022, 10, 8);
        Date d2(d1);
        Date d3(d1);
        Date d4(d1);

        (++d1).Print(); // d1.operator++()
        d1.Print();

        (d2++).Print(); // d2.operator++(1)
        d2.Print();

        (--d1).Print(); // d1.operator--()
        d1.Print();

        (d2--).Print(); // d2.operator--(1)
        d2.Print();
}

void TestDate3()
{
        Date d1(2022, 10, 10);
        Date d2(2023, 7, 1);

        cout << d2 - d1 << endl;
        cout << d1 - d2 << endl;
}

void TestDate4()
{
        Date d1, d2;

        cin >> d1 >> d2;
        cout << d1 << d2 << endl; // operator<<(cout, d1);
        cout << d1 - d2 << endl;
}

int main()
{
        //TestDate1();
        TestDate4();
        return 0;
}
以上就是C++实现日期类的示例详解的详细内容,更多关于C++日期类的资料请关注中国红客联盟其它相关文章!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行