C++:日期类的实现 const修饰 取地址及const取地址操作符重载(类的6个默认成员函数完结篇)

一、日期类的实现

根据之前赋值运算符重载逻辑,我们现在来实现完整的日期类。

1.1 判断小于

上篇博客已经实现:

bool operator<(const Date& d)
{if (_year < d._year){return true;}else if (_year == d._year){if (_month < d._month){return true;}else if (_month == d._month){if (_day < d._day){return true;}}}return false;
}

1.2 判断等于

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

1.3 判断小于等于

  • 根据1.1和1.2,我们可以直接复用。
bool operator<=(const Date& d)
{return *this <= d || *this == d;
}
  • 假如要判断d1是否小于等于d2,那就是d1相当于*this,d2相当于d

1.4 判断大于

  • 在这里我们改变一下思路,不需要像判断小于那样if嵌套,正因为已经实现了小于,我们直接取反就可以实现大于了
bool operator>(const Date& d)
{return !(*this <=d);
}

1.5 判断大于等于

这里小于取反

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

1.6 判断不等于

这里等于取反

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

1.7 获取月份天数

因为有闰年的存在,所以我们必须先实现获取月份天数才能确保加减天数

  • 因为这里的获取月份天数需要被频繁调用,我们这里声明和定义就不分离了(本质就是内联函数inline)
  • 放到静态区,好处是避免重复调用而导致数组重复生成
inline int GetMonthDay(int year,int month)
{assert(month < 13 && month > 0);//这里记得加上头文件#include<>static int MonthDays[13]={0,31,28,31,30,31,30,31,31,30,31,30,31 };// 先判断月份if (month == 2 && (((year % 100 == 0) && (year % 4 == 0)) || (year % 400 != 0)))return 29;return MonthDays[month];
}

1.8 日期加等天数

获取到月份天数后,我们就可以往下实现了。

  • 首先加上天数,判断当前月的天数和加上的天数
  • 然后进行减掉天数,月份+1,如果月份等于了13,年就+1,月份赋值为1
Date& operator+=(int day)
{// 这里就直接修改了_day += day;while (_day > GetMonthDay(_year, _month)){_day -= GetMonthDay(_year, _month);++_month;if (_month == 13){++_year;_month = 1;}}return *this;
}

1.9 日期加天数(本身不能改变)

  • 与日期加等天数不同,这里需要另外开一块空间,修改别的空间才不会影响这里的值
  • 这里不可以用引用返回(出了作用域还在才能使用引用返回),tmp是一个临时对象,必须用传值返回
Date operator+(int day)
{Date tmp(*this);//拷贝构造tmp._day += day;while (tmp._day > GetMonthDay(tmp._year, tmp._month)){tmp._day -= GetMonthDay(tmp._year, tmp._month);++tmp._month;if (tmp._month == 13){++tmp._year;tmp._month = 1;}}return tmp;
}
  • +=和+很相似,所以可以用+复用+=
Date operator+(int day)
{Date tmp(*this);tmp += day;return tmp;
}
  • 也可以用+=复用+
Date& operator+=(int day)
{*this = *this + day;return *this;
}

总体而言用+复用+=会更好,因为+里面会创建临时对象


1.10 日期减等天数

思路与上面加等一致

Date& operator-=(int day)
{_day -= day;while (_day <= 0){--_month;if (_month == 0){--_year;_month = 12;}_day += GetMonthDay(_year, _month);}return *this;
}

1.11 日期减天数

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

二、前置++和后置++重载

  • 前置++
Date& operator++()
{*this += 1;return *this;
}
  • 为了与前置++区分,增加一个int形参,能够构成重载区分
  • 后置++是要返回++以后的值
Date operator++(int)
{Date tmp = *this;*this += 1;return tmp;
}

三、日期-日期

int operator-(const Date& d)
{int flag = 1;Date max = *this;Date min = d;if (*this < d){int flag = -1;max = d;min = *this;}// 相差天数int n = 0;while (min != max){++min;++n;}return n * flag;
}

四、const修饰

4.1 const成员函数

  • 定义:将const修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。

在这里插入图片描述

class Date
{
public:Date(int year, int month, int day){_year = year;_month = month;_day = day;}void Print(){cout << "Print()" << endl;cout << "year:" << _year << endl;cout << "month:" << _month << endl;cout << "day:" << _day << endl << endl;}void Print(){cout << "Print()const" << endl;cout << "year:" << _year << endl;cout << "month:" << _month << endl;cout << "day:" << _day << endl << endl;}
private:int _year; // 年int _month; // 月int _day; // 日
};
void Test()
{Date d1(2022,1,13);d1.Print();const Date d2(2022,1,13);d2.Print();
}

我们一起来运行一下:
在这里插入图片描述

  • 这里是const对象去调用非const成员函数

  • 这里会出现一个权限放大的问题

  • 因此参数要改为 const Date*

所以要解决这个问题,我们要在第二个Print成员函数处加上一个const,如下图:
(这里的const修饰的是this指针指向的内容)
在这里插入图片描述


  • 下面图片为非const对象和const对象同时调用const成员函数

在这里插入图片描述
根据运行结果可以看到:非const对象是可以调用const成员函数的(因为这是权限的缩小)


既然非const对象和const对象都可以调用const成员函数,那我们是否可以将所有函数都加上const呢?
答案是不能的~
因为如果函数内部要被修改,那肯定是不能加的。

4.2 const修饰总结

  • 成员函数如果是一个对成员变量只进行读访问的函数,一般加上const,这样const对象和非const对象都可以访问

  • 成员函数如果是一个对成员变量进行读写访问的函数,不可以加上const,因为不能修改成员变量

下面集中总结4个问题:

  1. const对象可以调用非const成员函数吗? > 不可以(权限放大)
  2. 非const对象可以调用const成员函数吗? > 可以(权限缩小)
  3. const成员函数内可以调用其它的非const成员函数吗?> 不可以(权限放大)
  4. 非const成员函数内可以调用其它的const成员函数吗?> 可以(权限缩小)

五、取地址及const取地址操作符重载

前面几篇博客我们已经聊过前面4个默认成员函数,最后再来看看这最后两个吧~(了解即可)
在这里插入图片描述
这两个默认成员函数一般不用重新定义 ,编译器默认会生成。

class Date
{ 
public :Date* operator&(){return this ;}const Date* operator&()const{return this ;}
private :int _year ; int _month ; int _day ; 
};

这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要重载,比如想让别人获取到指定的内容

六、日期类的实现【源码】

#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 (!CheckInvalid()){cout << "构造日期非法" << endl;}}// 判断等于bool operator==(const Date& d){return _year == d._year&& _month == d._month&& _day == d._day;}// 判断小于bool operator<(const Date& d){if (_year < d._year){return true;}else if (_year == d._year){if (_month < d._month){return true;}else if (_month == d._month){if (_day < d._day){return true;}}}return false;}// 判断小于等于bool operator<=(const Date& d){return *this <= d || *this == d;}// 判断大于bool operator>(const Date& d){return !(*this <= d);}// 判断大于等于bool operator>=(const Date& d){return !(*this < d);}// 判断不等于bool operator!=(const Date& d){return !(*this == d);}// 日期加等天数Date& operator+=(int day){_day += day;while (_day > GetMonthDay(_year, _month)){_day -= GetMonthDay(_year, _month);++_month;if (_month == 13){++_year;_month = 1;}}return *this;}Date operator+(int day){Date tmp(*this);//Date tmp = *this;tmp += day;return tmp;}// 日期加天数Date operator+(const Date& d){Date tmp(*this);tmp._day += d._day;while (d._day > GetMonthDay(tmp._year, tmp._month)){tmp._day -= GetMonthDay(tmp._year, tmp._month);++tmp._month;if (tmp._month == 13){++tmp._year;tmp._month = 1;}}return tmp;}// 日期-=天数Date& operator-=(int day){_day -= day;while (_day <= 0){--_month;if (_month == 0){--_year;_month = 12;}_day += GetMonthDay(_year, _month);}return *this;}// 日期减天数Date operator-(int day){Date tmp = *this;tmp -= day;return tmp;}// 前置++Date& operator++(){*this += 1;return *this;}// 后置++Date operator++(int){Date tmp = *this;*this += 1;return tmp;}// 日期-日期int operator-(const Date& d){int flag = 1;Date max = *this;Date min = d;if (*this < d){int flag = -1;max = d;min = *this;}int n = 0;while (min != max){++min;++n;}return n * flag;}inline int GetMonthDay(int year, int month){assert(month < 13 && month > 0);// 放到静态区static int MonthDays[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };// 先判断月份if (month == 2 && (((year % 100 == 0) && (year % 4 == 0)) || (year % 400 != 0)))return 29;return MonthDays[month];}// 拷贝构造Date& operator=(const Date& d){if (this != &d){_year = d._year;_month = d._month;_day = d._day;}return *this;}friend ostream& operator<<(ostream& out, const Date& d);friend istream& operator>>(istream& in, Date& d);bool CheckInvalid(){if (_year <= 0|| _month < 1|| _month > 12|| _day < 1|| _day > GetMonthDay(_year,_month)){return false;}else{return true;}}void Print(){cout << _year << "/" << _month << "/" << _day << endl;}
private:int _year;int _month;int _day;
};ostream& operator<<(ostream& out, const Date& d)
{out << d._year << "年" << d._month << "月" << d._day << "日" << endl;return out;
}istream& operator>>(istream& in, Date& d)
{while (1){cout << "请依次输入年月日:>";in >> d._year >> d._month >> d._day;if (!d.CheckInvalid()){cout << "输入非法日期,请重新输入" << endl;}else{break;}}return in;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/805823.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

总结C/C++中程序内存区域划分

C/C程序内存分配的几个区域&#xff1a; 1. 栈区&#xff08;stack&#xff09;&#xff1a;在执行函数时&#xff0c;函数内局部变量的存储单元都可以在栈上创建&#xff0c;函数执行结束时这些存储单元自动被释放。栈内存分配运算内置于处理器的指令集中&#xff0c;效率很⾼…

KISS 原则和 YAGNI原则

设计模式专栏&#xff1a;http://t.csdnimg.cn/3a25S 目录 1.引言 2.代码并非行数越少越简单 3.代码复杂不一定违反 KISS 原则 4.如何写出满足 KISS 原则的代码 5.YAGNI原则和 KISS 原则的区别 1.引言 KISS原则的英文描述有3种版本:Keep It Simple and Supid、 keep It Sh…

OpenHarmony开发技术:【国际化】实例

国际化 如今越来的越多的应用都走向了海外&#xff0c;应用走向海外需要支持不同国家的语言&#xff0c;这就意味着应用资源文件需要支持不同语言环境下的显示。本节就介绍一下设备语言环境变更后&#xff0c;如何让应用支持多语言。 应用支持多语言 ArkUI开发框架对多语言的…

Autowired和Resource的关系?

相同点 对于下面的代码来说&#xff0c;如果是Spring容器的话&#xff0c;两个注解的功能基本是等价的&#xff0c;他们都可以将bean注入到对应的field中 Autowired private Bean beanA; Resource private Bean beanB; 不同点 byName和byType匹配顺序不同 Autowired在获取…

TypeScript—详解、小案例(配合源代码)

简介&#xff1a;TypeScript是微软开发的 JavaScript 的超集&#xff0c;TypeScript兼容JavaScript&#xff0c;可以载入JavaScript代码然后运行。TypeScript与JavaScript相比进步的地方 包括&#xff1a;加入注释&#xff0c;让编译器理解所支持的对象和函数&#xff0c;编译器…

Web路径专题

文章目录 1.资源定位1.前置条件上下文路径设置 2.上下文路径介绍重点说明 3.资源定位方式资源路径 上下文路径 资源位置a.html定位C.java定位 4.浏览器和服务器解析的区别1.浏览器解析/&#xff08;地址变化&#xff09;2.服务器解析/&#xff08;地址不变&#xff09; 5.带/…

备份工具--kopia

kopia 备份测试 安装minio wget https://dl.min.io/server/minio/release/linux-amd64/minio 创建目录 mkdir -p /data/myapp/minio mkdir -p /data/minidata 配置启动 cat start_minio.sh nohup /data/myapp/minio/minio server --console-address :“9090” /data/minidata…

数据流重定向

数据流重定向 标准输入 0 标准输出 1 标准错误输出 2 输出 > 标准输出 1>标准错误输出 2>标准输出标准错误输出 2>&1 或 &> 输入 < 标准输入 0<eof输入 cat > catfile <<“eof” 双向重定向 tee [command] | tee -a [file] [comma…

Spring和Spring MVC和MyBatis面试题

面试题1&#xff1a;请简述Spring、Spring MVC和MyBatis在整合开发中的作用&#xff1f; 答案&#xff1a; Spring&#xff1a;是一个轻量级的控制反转&#xff08;IoC&#xff09;和面向切面&#xff08;AOP&#xff09;的容器框架。它提供了强大的依赖注入功能&#xff0c;…

git学习 1

打开自己想要存放git仓库的文件夹&#xff0c;右键打开git bush&#xff0c;用git init命令建立仓库 用 ls -a(表示全都要看&#xff0c;包括隐藏的)可以看到git仓库 也可以用 git clone 接github链接&#xff08;点code选项里面会给链接&#xff0c;结尾是git的那个&#xf…

程序员开发指南-- reference

01. 项目介绍 为开发人员分享快速参考备忘清单【速查表】 GitHub - jaywcjlove/reference: 为开发人员分享快速参考备忘清单(速查表) 02. 部署Quick Reference网站 docker pull wcjiang/reference docker run --name reference --rm -d -p 9667:3000 wcjiang/reference:lat…

阿里云ACK k8s集群迁移

1、创建k8s集群 阿里云ACK创建 2、创建所需的第三方插件 ACK ingress创建 3、导出原有ACK集群配置 包含deployment、service、ingress、PersistentVolumeClaim 执行命令 kubectl get deployment,service,secret,ingress,PersistentVolumeClaim -n <namespace_name> -o y…

OpenHarmony南向开发实例:【智能可燃气体检测系统】

样例简介 本项目是基于BearPi套件开发的智能可燃气体检测Demo&#xff0c;该系统内主要由小熊派单板套件和和MQ5可燃气体检测传感器组成。 智能可燃气体检测系统可以通过云和手机建立连接&#xff0c;可以在手机上控制感应的阈值&#xff0c;传感器感知到的可燃气体浓度超过阈…

【ISO体系认证】云服务信息安全管理体系,一起来看看吧!

云服务信息安全管理体系&#xff08;简称“CSISMS”&#xff09;&#xff0c;以ISO/IEC 27017:2015为认证依据。ISO/IEC 27017标准是建立在ISO/IEC 27001信息安全管理体系框架和ISO/IEC 27002作为最佳实践控制设置的坚实基础之上&#xff0c;通过ISO/IEC 27017标准认证&#xf…

C++ | Leetcode C++题解之第12题整数转罗马数字

题目&#xff1a; 题解&#xff1a; const string thousands[] {"", "M", "MM", "MMM"}; const string hundreds[] {"", "C", "CC", "CCC", "CD", "D", "DC&qu…

azkaban的写法

先创建一个.job文件和一个.sql文件 sql语法写到一个test名字的文件里&#xff0c;之后job写法如下&#xff1a; typecommand commandhive -f test6.sql 一定要严格写&#xff0c;不管是字母还是空格&#xff0c;单引号中就是sql文件的名字 然后将它们一块打包&#xff0c;启动…

ubuntu系统逻辑卷Logical Volume扩容根分区

Linux LVM详解 https://blog.csdn.net/qq_35745940/article/details/119054949 https://blog.csdn.net/weixin_41891696/article/details/118805670 https://blog.51cto.com/woyaoxuelinux/1870299 LVM&#xff08;Logical Volume Manager&#xff09;逻辑卷管理&#xff0c…

Go语言开发小技巧易错点100例(十四)

往期回顾&#xff1a; Go语言开发小技巧&易错点100例&#xff08;一&#xff09;Go语言开发小技巧&易错点100例&#xff08;二&#xff09;Go语言开发小技巧&易错点100例&#xff08;三&#xff09;Go语言开发小技巧&易错点100例&#xff08;四&#xff09;Go…

贪心算法|452.用最少数量的箭引爆气球

力扣题目链接 class Solution { private:static bool cmp(const vector<int>& a, const vector<int>& b) {return a[0] < b[0];} public:int findMinArrowShots(vector<vector<int>>& points) {if (points.size() 0) return 0;sort(p…

rk3588开发板上安装ssh服务

目的&#xff1a;实现远程访问和控制&#xff0c;其他主机远程控制rk3588 方法及操作步骤&#xff1a; 1&#xff09;安装&#xff1a;sudo apt install openssh-server 2&#xff09; 查看运行状态 sudo systemctl status ssh 其它主机远程连接该开发板的ip和端口22即可