【C++】类和对象--一篇带你解决运算符重载实例--日期类
本篇文章我们将实现下面下面这些函数接口代码语言javascriptAI代码解释class Date { public: // 获取某年某月的天数 int GetMonthDay(int year, int month); // 全缺省的构造函数 Date(int year 1900, int month 1, int day 1); // 拷贝构造函数 //d2(d1) Date(const Date d); // 赋值运算符重载 // d2 d3 - d2.operator(d2, d3) Date operator(const Date d); // 析构函数 ~Date(); // 日期天数 Date operator(int day); // 日期天数 Date operator(int day); // 日期-天数 Date operator-(int day); // 日期-天数 Date operator-(int day); // 前置 Date operator(); // 后置 Date operator(int); // 后置-- Date operator--(int); // 前置-- Date operator--(); // 运算符重载 bool operator(const Date d); // 运算符重载 bool operator(const Date d); // 运算符重载 inline bool operator (const Date d); // 运算符重载 bool operator (const Date d); // 运算符重载 bool operator (const Date d); // !运算符重载 bool operator ! (const Date d); // 日期-日期 返回天数 int operator-(const Date d); private: int _year; int _month; int _day; };我们可以采用多文件的形式储存1. 全缺省的构造函数构造函数其实就是初始化的一个过程尤其注意的是对于日期的一个合法性的判断。但是因为月份的天数的细微差距这里调用一个GetMonthDay()函数接口来完成代码语言javascriptAI代码解释int Date::GetMonthDay(int year, int month) { assert(year 0 month 13 month0); //开辟一个静态区间用来解决不同月份的天数不同 static int monthDayAraay[13] { 0,31,28,31,30,31,30,31,31,30,31,30,31 }; if (month 2 isLeapYear(month)) { return 29; } return monthDayAraay[month]; }这里因为月份对应的天数是固定的所以我们选择将每个月的天数储存在一个静态数组中这样一来就可以做到一次的开辟之后可以进行多次的调用。同时因为二月天数收年份影响所以这里继续编写一个判断是都为闰年的函数接口isLeapYear()如果十二月份并且是闰年则直接返回29代码语言javascriptAI代码解释bool isLeapYear(int year) { return (year % 100 ! 0 year % 4 0) || (year % 400 0); }上面就是我们应该在构造函数中进行的日期是否合法的判断所以我们最终的构造函数应该是代码语言javascriptAI代码解释Date::Date(int year, int month, int day) { if (year 0 month 13 month0 day 0 day GetMonthDay(year,month)) { _year year; _month month; _day day; } else { cout 日期不合翻 endl; exit(-1); } }2. opeartor 判断两个日期是否相等很简单只需要将年月日的比较结果进行与逻辑判断即可代码语言javascriptAI代码解释bool Date::operator (const Date d) { return _year d._year _month d._month _day d._day; }3. operator 要想判断日期日期先比较year如果year小的话后面就无须比较了直接返回ture如果year相等就比较month如果month小的话后面也无须比较直接返回ture如果year、month都相等时最后才比较day如果day小直接返回ture
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2417191.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!