【C++类和对象】类有哪些默认成员函数呢?(下)

文章目录

  • 一、类的6个默认成员函数
  • 二、日期类的实现
    • 2.1 运算符重载部分
    • 2.2 日期之间的运算
    • 2.3 整体代码
      • 1.Date.h部分
      • 2. Date.cpp部分
  • 三. const成员函数
  • 四. 取地址及const取地址操作符重载
    • 扩展内容
  • 总结


ヾ(๑╹◡╹)ノ" 人总要为过去的懒惰而付出代价ヾ(๑╹◡╹)ノ"


一、类的6个默认成员函数

如果一个类中什么成员都没有,简称为空类。

空类中并不是什么都没有,任何类在什么都不写时,编译器会自动生成以下6个默认成员函数。
​​​​​​​​在这里插入图片描述
默认成员函数:用户没有显式实现,编译器会生成的成员函数称为默认成员函数

二、日期类的实现

2.1 运算符重载部分

  • inline不支持声明与定义分离,所以成员函数要成为inline,最好直接在类里面定义
  • 类里面定义成员函数的默认就是inline。代码较长的部分采用声明与定义分离的方法

1. 运算符重载部分1
此部分在Date.h类里面部分

//运算符重载部分1bool operator==(const Date& d);bool operator<(const Date& 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);}//思路:把小于的情况写出来,剩下的就是大于的情况bool operator<=(const Date& d){return *this < d || *this == d;//this是一个指针,指向类的指针//小于和等于都已经实现过了,所以就可以复用}//运算符重载部分,【+-】Date operator+(int day) const;Date& operator+=(int day);Date operator-(int day) const;Date& operator-=(int day);
  • 运算符重载部分【比较大小】,能复用其他函数的时候,尽可能的去复用
  • 此部分写一个小于等于,那么别的函数就都可以复用
  • 内联函数声明定义不能分离(符号表里没有函数的地址,所以使用的时候找不到函数定义),所以这部分代码,如果想设置成inline函数,就直接放到类里面。内联函数是在调用的地方,被展开,以空间换取时间的方法
  • 类里面的函数默认是内联函数

2. 运算符重载部分2
此部分在Date.cpp部分

//运算符重载部分2,==和<部分,
bool Date::operator==(const Date& d)//访问的本质上是:this->_year == d._year(一个是指针访问,一个是类直接访问)……//_year并不是类里面的_year(仅仅是一个声明),而是比较的另一个类
{if (_year == d._year&& _month == d._month&& _day == d._day){return true;}else{return false;}
}
bool Date::operator<(const Date& d)//要加上Date::(在类外面写)
{if (_year < d._year|| (_year == d._year && _month < d._month)|| (_year == d._year && _month == d._month && _day < d._day)){return true;}else{return false;}
}
//运算符重载
//d1+2=d2;因为此处运算符是+,d1是不变的,所以,不能直接对d1进行改动
Date Date::operator+(int day) const//这里的返回值不能用Date&,因为出了函数,空间就被回收了
{//+复用+=Date ret(*this);//拷贝构造ret += day;return ret;//Date ret(*this);//拷贝构造//ret._day += day;//while (ret._day > GetMonthDay(ret._year, ret._month))//{//	ret._day = ret._day - GetMonthDay(ret._year, ret._month);//	ret._month++;//	while (ret._month > 13)//	{//		ret._month = 1;//		ret._year++;//	}//}//return ret;
}Date& Date::operator+=(int day)//因为出了作用域this还在,所以用引用比较好【在能用引用的情况下,尽可能去用引用】
{//+=复用+//*this = *this + day;//return *this;if (day < 0){return *this -= -day;}_day += day;while (_day > GetMonthDay(_year, _day)){_day -= GetMonthDay(_year, _day);_month++;if (_month = 13){_month = 1;_year++;}}return *this;
}Date Date::operator-(int day) const
{Date ret(*this);ret -= day;return ret;
}
Date& Date::operator-=(int day)
{if (day < 0){return *this += -day;}_day -= day;while (_day <= 0)//日期是不能有0日的{_month--;while (_month == 0){_month = 12;_year--;}_day += GetMonthDay(_year, _month);}return *this;
}
  • 运算法重载部分【比较大小】
    因为代码较长,不适合用inline函数,所以使用声明与定义的方法【==和<的代码更加容易实现】
  • 运算符重载部分【+、+=、-、-=】
  • d1=10,注意:这里是+和-,并不是+=和-=,所以d1是不变的,不要对d1直接进行改动。【利用拷贝构造】
  • +和+=之间和-和-=之间可以相互复用【写整块代码的时候,代码之间能相互复用,就相互复用【即简单又很大程度上保证了代码的正确性】】【+复用+=更优】
  • 加减法注意:这里的day要求必须是正数,否则减去一个负数,相当于加上一个正数;加上一个负数,相当于减去一个正数(相互复用即可)【因为-复用-=,所以-的函数就不用考虑负数问题】

补充知识点(1):
Date d1(2000, 9, 17); Date d2 = d1;//这里是拷贝构造,不是赋值【因为一个已经创建的对象去初始化另一个对象就是拷贝构造】
【赋值是两个已经创建好的对象进行初始化】
补充知识点(2):
写赋值重载函数和拷贝构造函数时,函数的形参要加const,因为既可以防止修改值,又可以防止当形参是函数的返回值【具有const属性】,会权限扩大,导致错误【无法修改的右值】。


2.2 日期之间的运算

前置++后置++,前置–,后置–【区分++是前置还是后置的,函数重载】
C++用无参数的代表前置,有一个参数的代表后置【参数只要是int类型的就符合要求,无论是整形的哪一个数字】
1. 日期之间的运算1
此部分在Date.h类里面部分
Date.h

//日期之间的运算Date& operator++(){*this += 1;return *this;}Date operator++(int){Date tmp(*this);tmp += 1;return tmp;}Date& operator--(){*this -= 1;return *this;}Date operator--(int){Date tmp(*this);tmp -= 1;return tmp;}//日期-日期int operator-(const Date& d) const;

2. 日期之间的运算2
此部分在Date.cpp里面部分
Date.c

//*this和d不确定哪一个日期大
int Date::operator-(const Date& d) const
{int day = 0;int flag = 1;Date max = *this;Date min = d;if (*this < d){max = d;min = *this;flag = -1;}while (min != max){min++;day++;}day = day * flag;return day;
}

2.3 整体代码

1.Date.h部分

#pragma once#include <iostream>
#include <assert.h>
using std::cin;
using std::cout;//在正式的项目中不要全展开
using std::endl;class Date
{
public://拷贝构造函数部分//判断是否是闰年bool isLeapYear(int year){if (year % 4 == 0 && year % 100 != 0&& year % 400 == 0){return true;}return false;}//每一月的天数int GetMonthDay(int year, int month);//构造函数(也可以不用写)//可能会有用户输入非法日期Date(int year = 1, int month = 1, int day = 1);//拷贝构造函数(也可以不用写),值拷贝Date(const Date& d){_year = d._year;_month = d._month;_day = d._day;}//赋值运算符重载Date& operator=(const Date& d){if (this != &d){_year = d._year;_month = d._month;_day = d._day;}return *this;}//不需要写析构函数,没有资源清理//打印Date,在函数后面加一个const,相当于void print(const Date* const d),const对象和普通对象都可以调用此函数//如果不加const,相当于void print(Date* const d),//只要不修改this,就可以加上void print() const{cout << _year << "-" << _month << "-" << _day << endl;}//运算符重载部分,【+-】Date operator+(int day) const;Date& operator+=(int day);Date operator-(int day) const;Date& operator-=(int day);//运算符重载部分1【比较大小】bool operator==(const Date& d) const;bool operator<(const Date& d) const;bool operator>(const Date& d) const{return !(*this <= d);}bool operator>=(const Date& d) const{return !(*this < d);}bool operator!=(const Date& d) const{return !(*this == d);}//思路:把小于的情况写出来,剩下的就是大于的情况bool operator<=(const Date& d) const{return *this < d || *this == d;//this是一个指针,指向类的指针//小于和等于都已经实现过了,所以就可以复用}//日期之间的运算Date& operator++(){*this += 1;return *this;}Date operator++(int){Date tmp(*this);tmp += 1;return tmp;}Date& operator--(){*this -= 1;return *this;}Date operator--(int){Date tmp(*this);tmp -= 1;return tmp;}//日期-日期int operator-(const Date& d) const;private:int _year;int _month;int _day;
};

2. Date.cpp部分

#define _CRT_SECURE_NO_WARNINGS 1
#include "Date.h"//构造函数部分
Date::Date(int year = 1, int month = 1, int day = 1)
{if (year >= 1&& (month >= 1 && month <= 12)&& (day >= 1 && day <= GetMonthDay(year, month))){_year = year;_month = month;_day = day;}else{cout << "日期非法" << endl;}
}
int Date::GetMonthDay(int year, int month)
{assert(year > 0 && month >= 1 && month < 13);static int monthDayArray[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };//因为这部分空间需要频繁开辟,所以就用static,就可以节约时间if (month == 2 && isLeapYear(year)){return 29;}else{return monthDayArray[month];}
}//运算符重载部分2,
bool Date::operator==(const Date& d) const//访问的本质上是:this->_year == d._year(一个是指针访问,一个是类直接访问)……//_year并不是类里面的_year(仅仅是一个声明),而是比较的另一个类
{if (_year == d._year&& _month == d._month&& _day == d._day){return true;}else{return false;}
}
bool Date::operator<(const Date& d) const//要加上Date::(在类外面写)
{if (_year < d._year|| (_year == d._year && _month < d._month)|| (_year == d._year && _month == d._month && _day < d._day)){return true;}else{return false;}
}//运算符重载
//d1+2=d2;因为此处运算符是+,d1是不变的,所以,不能直接对d1进行改动
Date Date::operator+(int day) const//这里的返回值不能用Date&,因为出了函数,空间就被回收了
{//+复用+=Date ret(*this);//拷贝构造ret += day;return ret;//Date ret(*this);//拷贝构造//ret._day += day;//while (ret._day > GetMonthDay(ret._year, ret._month))//{//	ret._day = ret._day - GetMonthDay(ret._year, ret._month);//	ret._month++;//	while (ret._month > 13)//	{//		ret._month = 1;//		ret._year++;//	}//}//return ret;
}Date& Date::operator+=(int day)//因为出了作用域this还在,所以用引用比较好【在能用引用的情况下,尽可能去用引用】
{//+=复用+//*this = *this + day;//return *this;if (day < 0){return *this -= -day;}_day += day;while (_day > GetMonthDay(_year, _day)){_day -= GetMonthDay(_year, _day);_month++;if (_month = 13){_month = 1;_year++;}}return *this;
}Date Date::operator-(int day) const
{Date ret(*this);ret -= day;return ret;
}
Date& Date::operator-=(int day)
{if (day < 0){return *this += -day;}_day -= day;while (_day <= 0)//日期是不能有0日的{_month--;while (_month == 0){_month = 12;_year--;}_day += GetMonthDay(_year, _month);}return *this;
}//*this和d不确定哪一个日期大
int Date::operator-(const Date& d) const
{int day = 0;int flag = 1;Date max = *this;Date min = d;if (*this < d){max = d;min = *this;flag = -1;}while (min != max){min++;day++;}day = day * flag;return day;
}

三. const成员函数

将const修饰的类成员函数称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。
Date类中的打印函数中

	void print() const{cout << _year << "-" << _month << "-" << _day << endl;}
  • 打印Date,在函数后面加一个const,相当于void print(const Date* const d),const对象和普通对象都可以调用此函数
  • 如果不加const,相当于void print(Date* const d),
  • 只要不修改this,就可以加上const
  • (d+13).print();会报错,因为d+13是传值返回,传值返回的是临时拷贝,临时拷贝具有常性。【在print没有加const的情况下】

建议成员函数中,不修改成员变量的成员函数,都可以加上const。【普通对象和const对象都可以调用】 不加const,那么const修饰的对象就没有办法调用成员函数

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

四. 取地址及const取地址操作符重载

这两个默认成员函数一般不用重新定义 ,编译器默认会生成。

	Date* operator&(){return this;}//取地址重载const Date* operator&() const{return this;}//const取地址重载

这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要重载,比如想让别人获取到指定的内容【不想要输出地址,而是别的内容】!【此时才需要我们自己写】


扩展内容

流插入运算符和流提取运算符重载
d1.operator<<(cout);//test函数中写,可以运行
cout<<d1;//不可以运行
void operator<<(std::ostream out)
{
out << _year<< “- “<< _month<<” -” << _day<<endl;
}
Date.h 类里面

//友元函数friend std::ostream& operator<<(std::ostream& out, const Date& d);friend std::istream& operator>>(std::istream& in, Date& d);

Date.cpp

std::ostream& operator<<(std::ostream& out, const Date& d)
{out << d._year << "-" << d._month << "-" << d._day << endl;return out;
}
std::istream& operator>>(std::istream& in, Date& d)
{in >> d._year >> d._month >> d._day;return in;
}
  • 内置类型直接支持流插入和流提取【且自动识别类型,因为函数重载】
  • 全局变量函数不要放在.h里面,因为在别的文件展开的时候,会出现多个符号表里,导致重定义。【只有声明的时候,才会链接的时候去找函数】

总结

以上就是今天的所有内容了,类的默认成员函数就到此结束了。本文以及【C++类和对象】类有哪些默认成员函数呢?(上)】详细的介绍了类的默认成员函数,希望给友友们带来帮助!

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

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

相关文章

VS2019 + Qt : setToolTip的提示内容出现乱码

VS2019 Qt : setToolTip的提示内容出现乱码 在使用setToolTip()时&#xff0c; setToolTip(QString("asd你好&#xff01;");标签提示只有英文是对的&#xff0c;中文是乱码&#xff01; 应该是编码出了问题。默认情况下&#xff0c;Qt使用的是UTF-8编码&#xf…

分类预测 | MATLAB实现WOA-CNN-BiGRU-Attention数据分类预测

分类预测 | MATLAB实现WOA-CNN-BiGRU-Attention数据分类预测 目录 分类预测 | MATLAB实现WOA-CNN-BiGRU-Attention数据分类预测分类效果基本描述模型描述程序设计参考资料 分类效果 基本描述 1.Matlab实现WOA-CNN-BiGRU-Attention多特征分类预测&#xff0c;多特征输入模型&…

CMake教程6:调用lib、dll

之前我们学到了如何编写一个可执行程序和Library&#xff0c;在继续学习之前&#xff0c;需要解释下target&#xff0c;在cmake中我们可以给executable和library设置一个target名字&#xff0c;这样可以方便我们在后续对target进行更加详细的属性设置。 本节我们将学习如何在项…

mysql 03.查询(重点)

先准备测试数据&#xff0c;代码如下&#xff1a; -- 创建数据库 DROP DATABASE IF EXISTS mydb; CREATE DATABASE mydb; USE mydb;-- 创建student表 CREATE TABLE student (sid CHAR(6),sname VARCHAR(50),age INT,gender VARCHAR(50) DEFAULT male );-- 向student表插入数据…

【黑产攻防道02】如何对抗黑产的图像识别模型

全文8799字&#xff0c;预计阅读时间约25分钟&#xff0c;建议收藏后阅读 验证码本质上自带一层答案的语义&#xff0c;这是天然的区分人和自动程序的地方。无论使用哪一种方式破解验证码&#xff0c;都必须识别出答案。 在多年与黑产破解者的博弈对抗的过程中&#xff0c;我…

zabbix整合prometheus的数据

1 zabbix安装 官方文档参考 https://www.zabbix.com/download?zabbix6.0&os_distributioncentos&os_version7&componentsproxy&dbmysql&ws https://www.zabbix.com/download?zabbix4.0&os_distributioncentos&os_version7&componentsserver…

Jmeter 连接 MySQL 数据库脚本

1、创建线程组 2、创建 JDBC Connection Configuration 3、创建 JDBC Request 4、最终创建的目录 5、重点来了 5.1 在百度中下载个 MySQL-connector-Java-8.0.28.jar&#xff0c;放在 jmeter 的 bin 目录下 5.2 在测试计划中&#xff0c;将 jar 包添加到脚本中 5.3 输入参…

[Docker精进篇] Docker镜像构建和实践 (三)

前言&#xff1a; Docker镜像构建的作用是将应用程序及其依赖打包到一个可移植、自包含的镜像中&#xff0c;以便在不同环境中快速、可靠地部署和运行应用程序。 文章目录 Docker镜像构建1️⃣是什么&#xff1f;2️⃣为什么&#xff1f;3️⃣镜像构建一、用现有容器构建新镜像…

网络通信原理TCP字段解析(第四十七课)

字段含义Source Port(源端口号)源端口,标识哪

opencv实战项目-停车位计数

手势识别系列文章目录 手势识别是一种人机交互技术&#xff0c;通过识别人的手势动作&#xff0c;从而实现对计算机、智能手机、智能电视等设备的操作和控制。 1. opencv实现手部追踪&#xff08;定位手部关键点&#xff09; 2.opencv实战项目 实现手势跟踪并返回位置信息&a…

Wlan安全——认证与加密方式(WPA/WPA2)

目录 终端认证技术 WEP认证 PSK认证 802.1x认证与MAC认证 Portal认证 数据加密技术 WEP加密 TKIP加密 CCMP加密 TKIP和CCMP生成密钥所需要的密钥信息 802.11安全标准 WEP共享密钥认证、加密工作原理 WEP共享密钥认证 WEP加解密过程 PSK认证以及生成动态密钥的工…

NLP文本匹配任务Text Matching [无监督训练]:SimCSE、ESimCSE、DiffCSE 项目实践

NLP文本匹配任务Text Matching [无监督训练]&#xff1a;SimCSE、ESimCSE、DiffCSE 项目实践 文本匹配多用于计算两个文本之间的相似度&#xff0c;该示例会基于 ESimCSE 实现一个无监督的文本匹配模型的训练流程。文本匹配多用于计算两段「自然文本」之间的「相似度」。 例如…