【C++】:类和对象(中)之拷贝构造函数+赋值运算符重载

在这里插入图片描述
在这里插入图片描述

拷贝构造函数

概念

在现实生活中,可能存在一个与你一样的自己,我们称其为双胞胎
在这里插入图片描述
那在创建对象时,可否创建一个与已存在对象一某一样的新对象呢?
拷贝构造函数:只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型对象创建新对象时由编译器自动调用

特征

拷贝构造函数也是特殊的成员函数,其特征如下:

  1. 拷贝构造函数是构造函数的一个重载形式
  2. 拷贝构造函数的参数只有一个且必须是类类型对象的引用,使用传值方式编译器直接报错,因为会引发无穷递归调用
class Date
{
public:Date(int year = 1900, int month = 1, int day = 1){_year = year;_month = month;_day = day;}// Date(const Date& d)   // 正确写法Date(const Date& d)   // 错误写法:编译报错,会引发无穷递归{_year = d._year;_month = d._month;_day = d._day;}
private:int _year;int _month;int _day;
};
int main()
{Date d1;Date d2(d1);return 0;
}

在这里插入图片描述
这里大家可能会很疑惑为什么会出现无穷递归的现象 下面我画一个图大家理解一下
在这里插入图片描述

  1. 若未显式定义,编译器会生成默认的拷贝构造函数。 默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝
#include<iostream>
using namespace std;
class Date
{
public:Date(int year = 1900, int month = 1, int day = 1){_year = year;_month = month;_day = day;}Date(const Date& dd){_year = dd._year;_month = dd._month;_day = dd._day;}void Print(){cout << _year << "/" << _month << "/" << _day << endl;}
private:int _year;int _month;int _day;
};void func1(Date& d)
{d.Print();
}int main()
{//拷贝构造函数Date d1(2023, 10, 22);func1(d1);Date d2(d1);

注意:在编译器生成的默认拷贝构造函数中,内置类型是按照字节方式直接拷贝的,而自定义类型是调用其拷贝构造函数完成拷贝的
4. 编译器生成的默认拷贝构造函数已经可以完成字节序的值拷贝了,还需要自己显式实现吗?当然像日期类这样的类是没必要的。那么下面的类呢?验证一下试试?

class Stack
{
public:Stack(size_t capacity = 3){cout << "Stack(size_t capacity = 3)" << endl;_a = (int*)malloc(sizeof(int) * capacity);if (_a == nullptr){perror("malloc fail");/*exit(-1)*/return;}_capacity = capacity;_top = 0;}~Stack(){cout << "~Stack()" << endl;free(_a);_capacity = _top = 0;_a = nullptr;}Stack(const Stack& stt){//深拷贝_a = (int*)malloc(sizeof(int) * stt._capacity);if (_a == nullptr){perror("malloc fail");exit(-1);//return;}memcpy(_a, stt._a, sizeof(int) * stt._top);_top = stt._top;_capacity = stt._capacity;}
private:int* _a;int _capacity;int _top;
};
int main()
{//拷贝构造函数Date d1(2023, 10, 22);func1(d1);Date d2(d1);Stack st1;func2(st1);Stack st2(st1);

注意:类中如果没有涉及资源申请时,拷贝构造函数是否写都可以;一旦涉及到资源申请时,则拷贝构造函数是一定要写的,否则就是浅拷贝
在这里插入图片描述
5. 拷贝构造函数典型调用场景:
使用已存在对象创建新对象
函数参数类型为类类型对象
函数返回值类型为类类型对象

class Date
{
public:Date(int year, int minute, int day){cout << "Date(int,int,int):" << this << endl;}Date(const Date& d){cout << "Date(const Date& d):" << this << endl;}~Date(){cout << "~Date():" << this << endl;}
private:int _year;int _month;int _day;
};
Date Test(Date d)
{Date temp(d);return temp;
}
int main()
{Date d1(2022,1,13);Test(d1);return 0;
}

在这里插入图片描述
为了提高程序效率,一般对象传参时,尽量使用引用类型,返回时根据实际场景,能用引用尽量使用引用

赋值运算符重载

运算符重载

C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其
返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。
函数名字为:关键字operator后面接需要重载的运算符符号
函数原型:返回值类型 operator操作符(参数列表)
注意:
不能通过连接其他符号来创建新的操作符:比如operator
重载操作符必须有一个类类型参数
用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不能改变其含义
作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐
藏的this
.* :: sizeof ?: . 注意以上5个运算符不能重载。这个经常在笔试选择题中出现

// 全局的operator==
class Date
{ 
public:Date(int year = 1900, int month = 1, int day = 1){_year = year;_month = month;_day = day;}    
//private:int _year;int _month;int _day;
};
// 这里会发现运算符重载成全局的就需要成员变量是公有的,那么问题来了,封装性如何保证?
// 这里其实可以用我们后面学习的友元解决,或者干脆重载成成员函数。
bool operator==(const Date& d1, const Date& d2)
{return d1._year == d2._year&& d1._month == d2._month&& d1._day == d2._day;
}
void Test ()
{Date d1(2018, 9, 26);Date d2(2018, 9, 27);cout<<(d1 == d2)<<endl;
}
class Date
{ 
public:Date(int year = 1900, int month = 1, int day = 1){_year = year;_month = month;_day = day;}// bool operator==(Date* this, const Date& d2)// 这里需要注意的是,左操作数是this,指向调用函数的对象bool operator==(const Date& d2){return _year == d2._year;&& _month == d2._month&& _day == d2._day;}
private:int _year;int _month;int _day;
};

以下是我们关于赋值运算符重载的总代码

class Date
{
public:Date(int year = 1, int month = 1, int day = 1){_year = year;_month = month;_day = day;}void Print(){cout << _year << "/" << _month << "/" << _day << endl;}//int GetYear();bool operator==(const Date& y){return _year == y._year&& _month == y._month&& _day == y._day;}bool operator>(const Date& y){if (_year > y._year){return true;}else if (_year == y._year && _month > y._month){return true;}else if (_year == y._year && _month == y._month && _day > y._day){return true;}return false;}// d1 - d2int operator-(const Date& d){// ...return 0;}int GetMonthDay(int year, int month){assert(year >= 1 && month >= 1 && month <= 12);int monthArray[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;return monthArray[month];}// d1 += 100Date& operator+=(int day){_day += day;while (_day > GetMonthDay(_year, _month)){_day -= GetMonthDay(_year, _month);++_month;if (_month == 13){_year++;_month = 1;}}return *this;}// d1 + 50/*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;}private:int _year;int _month;int _day;
};int main()
{Date d1;Date d2(2023, 10, 22);bool ret1 = d1 > d2;  // d1.operator>(d2) -> d1.operator>(&d1, d2)bool ret2 = d1 == d2; // d1.operator==(d2) -> d1.operator==(&d1, d2)// d1.operator>(d2);// 一个重载哪些运算符呢?主要这个运算符有没有意义// 有意义就可以实现,没有意义就不要实现//d1 + d2;d1 - d2;//d1 * d2;//d1 / d2;d2 += 50;d2.Print();Date ret3 = d1 + 50;d1.Print();ret3.Print();int i = 0, j = 0;//i += 50;int ret = j += i += 50;return 0;
}

赋值运算符重载

  1. 赋值运算符重载格式
    参数类型:const T&,传递引用可以提高传参效率
    返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值检测是否自己给自己赋值
    返回*this :要复合连续赋值的含义
class Date
{ 
public :Date(int year = 1900, int month = 1, int day = 1){_year = year;_month = month;_day = day;}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;}
private:int _year ;int _month ;int _day ;
};
  1. 赋值运算符只能重载成类的成员函数不能重载成全局函数
class Date
{
public:Date(int year = 1900, int month = 1, int day = 1){_year = year;_month = month;_day = day;}int _year;int _month;int _day;
};
// 赋值运算符重载成全局函数,注意重载成全局函数时没有this指针了,需要给两个参数
Date& operator=(Date& left, const Date& right)
{if (&left != &right){left._year = right._year;left._month = right._month;left._day = right._day;}return left;
}
// 编译失败:
// error C2801: “operator =”必须是非静态成员

原因:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数
在这里插入图片描述
3. 用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。注意:内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值

class Time
{
public:Time(){_hour = 1;_minute = 1;_second = 1;}Time& operator=(const Time& t){if (this != &t){_hour = t._hour;_minute = t._minute;_second = t._second;}return *this;}
private:int _hour;int _minute;int _second;
};
class Date
{
private:// 基本类型(内置类型)int _year = 1970;int _month = 1;int _day = 1;// 自定义类型Time _t;
};
int main()
{Date d1;Date d2;d1 = d2;return 0;
}

前置++和后置++重载

class Date
{
public:Date(int year = 1900, int month = 1, int day = 1){_year = year;_month = month;_day = day;}// 前置++:返回+1之后的结果// 注意:this指向的对象函数结束后不会销毁,故以引用方式返回提高效率Date& operator++(){_day += 1;return *this;}// 后置++:// 前置++和后置++都是一元运算符,为了让前置++与后置++形成能正确重载// C++规定:后置++重载时多增加一个int类型的参数,但调用函数时该参数不用传递,编译器
自动传递// 注意:后置++是先使用后+1,因此需要返回+1之前的旧值,故需在实现时需要先将this保存
一份,然后给this+1//       而temp是临时对象,因此只能以值的方式返回,不能返回引用Date operator++(int){Date temp(*this);_day += 1;return temp;}
private:int _year;int _month;int _day;
};
int main()
{Date d;Date d1(2022, 1, 13);d = d1++;    // d: 2022,1,13   d1:2022,1,14d = ++d1;    // d: 2022,1,15   d1:2022,1,15return 0;
}

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

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

相关文章

怎么让英文大语言模型支持中文?--构建中文tokenization--继续预训练--指令微调

1 构建中文tokenization 参考链接&#xff1a;https://zhuanlan.zhihu.com/p/639144223 1.1 为什么需要 构建中文tokenization&#xff1f; 原始的llama模型对中文的支持不太友好&#xff0c;接下来本文将讲解如何去扩充vocab里面的词以对中文进行token化。 1.2 如何对 原始数…

单独使用logback作为日志

文章目录 引入logback的依赖logback.xml测试 具体配置&#xff0c;可参看&#xff1a;LogBack日志学习&#xff08;全面&#xff09; logback使用实战 log4j使用实战 log4j2使用实战 Java日志系统之Logback Java日志系统之Slf4j Java日志系统之Log4j 引入logback的依赖 …

JAVA观察者模式-案例

Java观察者模式 import java.util.ArrayList; import java.util.List; // 主题接口&#xff0c;定义了添加、删除观察者等方法 interface Subject { void register(Observer observer); void unregister(Observer observer); void notifyObservers(String message); …

FPGA的斐波那契数列Fibonacci设计verilog,代码和视频

名称&#xff1a;斐波那契数列Fibonacci设计verilog 软件&#xff1a;Quartus 语言&#xff1a;Verilog 代码功能&#xff1a; 设计一个产生斐波那契数列&#xff08;也叫黄金分割数列&#xff09;的硬件电路: 斐波那契数列中每个数为其相邻前两个数的和:即FNFN1FN2,(数列…

探索数据结构世界之排序篇章(超级详细,你想看的都有)

-文章开头必看 1.&#xff01;&#xff01;&#xff01;本文排序默认都是排升序 2.排序是否稳定值指指排完序之后相同数的相对位置是否改变 3.代码相关解释我都写在注释中了&#xff0c;方便对照着看 1.插入排序1.1直接插入排序1.2希尔排序1.2.1单趟1.2.2多趟基础版——排完一…

Python:函数篇(每周练习)

编程题&#xff1a; Python第四章作业&#xff08;初级&#xff09; (educoder.net) 题一&#xff1a;无参无返回值函数 def print_hi_human(): # 函数名用小写字母print("人类&#xff0c;你好&#xff01;")if __name__ __main__:print_hi_human() 题二&#…

DailyPractice.2023.10.22

文章目录 1.[39. 组合总和]2.[22. 括号生成]3.[79. 单词搜索]4.[131. 分割回文串] 1.[39. 组合总和] 39. 组合总和 class Solution { public: vector<vector<int>> res; vector<int> path;void dfs(vector<int>& candidates,int target,int star…

如何支持h.265视频

前言 略 h.265视频 h.265是一种视频编码格式。 随着视频编码技术的发展&#xff0c;相比H.264, H.265同等画质体积仅为一半、带宽占用省一半、画质更细腻等诸多优势。 但Web浏览器还不支持H.265的解码播放&#xff0c;因此基于Web Assembly(封装FFmpeg)、JS解封装、Canvas投…

【读书笔记】《软技能》

句子摘抄&#xff1a; 软技能-代码之外的生存指南 “自强不息 孜孜不倦” 强调了坚持不懈、不断奋斗和追求进步的精神。无论遇到多少困难和挫折&#xff0c;都要坚持努力&#xff0c;不断提高自己&#xff0c;不知疲倦地追求目标。这句谚语鼓励人们积极进取&#xff0c;不轻言…

设计模式篇---组合模式

文章目录 概念结构实例总结 概念 组合模式&#xff1a;组合多个对象形成树形结构以表示具有部分-整体关系的层次结构。组合模式让客户端可以统一对待单个对象和组合对象。 当我们开发中遇到树形结构的业务时&#xff0c;可以考虑使用组合模式。&#xff08;我也没有想明白为啥…

【3D 图像分割】基于 Pytorch 的 VNet 3D 图像分割1(综述篇)

在上一个关于3D 目标的任务&#xff0c;是基于普通CNN网络的3D分类任务。在这个任务中&#xff0c;分类数据采用的是CT结节的LIDC-IDRI数据集&#xff0c;其中对结节的良恶性、毛刺、分叶征等等特征进行了各自的等级分类。感兴趣的可以直接点击下方的链接&#xff0c;直达学习&…

在 Android 10 中访问/proc/net/route权限被拒绝

在 Android 10 中访问/proc/net/route权限被拒绝 问题分析完整代码问题 FileReader fr = new FileReader(“/proc/net/route”);在 Android 10 中访问/proc/net/route权限被拒绝 分析 运行/proc/net/route命令并处理其输出: val runtime = Runtime.getRuntime() val proc …

Mysql数据库 2.SQL语言 数据类型与字段约束

Mysql数据类型 数据类型&#xff1a;指的是数据表中的列文件支持存放的数据类型 1.数值类型 Mysql当中有多种数据类型可以存放数值&#xff0c;不同的类型存放的数值的范围或者形式是不同的 注&#xff1a;前三种数字类型我们在实际研发中用的很少&#xff0c;一般整数类型…

[论文笔记]NEZHA

引言 今天带来华为诺亚方舟实验室提出的论文NEZHA,题目是 针对中文中文语言理解神经网络上下文表示(NEural contextualiZed representation for CHinese lAnguage understanding),为了拼出哪吒。 预训练语言模型由于具有通过对大型语料库进行预训练来捕获文本中深层上下文信…

【每日一题Day352】LC1726同积元组 | 哈希表+排列组合

同积元组【LC1726】 给你一个由 不同 正整数组成的数组 nums &#xff0c;请你返回满足 a * b c * d 的元组 (a, b, c, d) 的数量。其中 a、b、c 和 d 都是 nums 中的元素&#xff0c;且 a ! b ! c ! d 。 思路 求出所有二元组的积及其出现次数&#xff0c;假设某个积出现的次…

空中计算(Over-the-Air Computation)学习笔记

文章目录 写在前面 写在前面 本文是论文A Survey on Over-the-Air Computation的阅读笔记&#xff1a; 通信和计算通常被视为独立的任务。 从工程的角度来看&#xff0c;这种方法是非常有效的&#xff0c;因为可以执行孤立的优化。 然而&#xff0c;对于许多面向计算的应用程序…

Docker镜像制作

目录 Dockfile是什么 构建镜像的三个步骤 dockerfile内容基础知识 docker执行一个Dockerfile脚本的大致流程 Dockerfile指令 FROM MAINTAINER RUN EXPOSE WORKDIR ENV ADD COPY VOLUME USER ONBUILD CMD ENTRYPOINT CMD和ENTRYPOINT区别 构建dockerfile Do…

shell之常见网络命令介绍

shell之常见网络命令介绍 1&#xff09;ifconfig 用于配置网络接口。可以用于开启、关闭和设置网络接口的参数&#xff0c;如IP地址、子网掩码、MAC地址等。 ifconfig eth0 192.168.1.1 netmask 255.255.255.0 up上述命令将设置eth0网络接口的IP地址为192.168.1.1&#xff0c;子…

leetcode(2)栈

leetcode 155 最小栈 stack相当于栈&#xff0c;先进后出 存储全部栈元素 [-3,2,-1] min_stack,存储栈当前位置最小的元素 [-3,-3,-3] class MinStack:def __init__(self):self.stack []self.min_stack [math.inf]def push(self, x: int) :self.stack.append(x)self.min_sta…

游戏反虚拟框架检测方案

游戏风险环境&#xff0c;是指独立于原有设备或破坏设备原有系统的环境。常见的游戏风险环境有&#xff1a;iOS越狱、安卓设备root、虚拟机、虚拟框架、云手机等。 因为这类风险环境可以为游戏外挂、破解提供所需的高级别设备权限&#xff0c;所以当游戏处于这些设备环境下&am…