C++类和对象:赋值重载,const成员,取地址及const取地址操作符重载

news2025/3/10 14:44:52

文章目录

    • 1.赋值运算符重载
      • 1.1运算符重载
      • 1.2 赋值运算符重载
      • 1.3 前置++和后置++重载
    • 2.日期类的实现
    • 3. const成员函数
    • 4 取地址及const取地址操作符重载

在这里插入图片描述
上文介绍了前三个默认成员函数,本文会介绍剩下三个, 赋值重载会重点展开。

1.赋值运算符重载

1.1运算符重载

C++为了增强代码的可读性引入了运算符重载运算符重载是具有特殊函数名的函数,也具有其
返回值类型函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。

函数名字为:关键字operator后面接需要重载的运算符符号
函数原型:返回值类型operator操作符(参数列表)

我们知道,类是不能用符号直接进行比较的,但如果要用 运算符 > 来比较类A是否大于类B,此时就可以重载运算符>:(Date类举例)

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	bool operator>(Date& tmp)
	{
		return this->_year > tmp._year;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d1(2024, 2, 2);
	Date d2(2021, 2, 2);
	//使用重载后d1和d2就可以按照自己设定的规则比较
	cout << (d1 > d2) << endl;
}

注意:

  1. 不能通过连接其他符号来创建新的操作符:比如operator@(本来@就不是运算符,不能重载)
  2. 重载操作符必须有一个类的类型参数
  3. 不能重载内置类型的运算符例如:内置的整型+,不 能改变其含义。
  4. 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this(下面的代码Date类做个解释):
class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	//看似只有一个参数,其实隐藏了一个固定的参数this,并且是固定的第一个参数
	bool operator>(Date& tmp)
	{
		return this->_year > tmp._year;
	}
private:
	int _year;
	int _month;
	int _day;
};
  1. 运算符重载后,可以显示调用,也可以转换调用,其反汇编指令完全相同:
//显示调用
d1 > d2;
//转换调用
d1.operator>(d2);

在这里插入图片描述

  1. .* :: sizeof ?: . 注意以上5个运算符不能重载。
    PS: .*用法:
class Date
{
public:
	//成员函数 f
	void fun()
	{

	}
private:
	int _year;
	int _month;
	int _day;
};
typedef void(Date::* Ptr)();//1.将 函数指针类型void(*)() 重命名为 Ptr ,并且指定在Date类内
int main()
{
	Ptr ptr = &Date::fun; // 2.void(*)()类型的 ptr 指向Date类内的成员函数
	Date test;//3.实例化test
	(test.*ptr)();//4. 通过ptr调用test的fun函数,就要用到.*
}

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)
	{
		_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. 赋值运算符重载格式
  • 参数类型:const T(类型)& ->传递引用可以提高传参效率
  • 返回值类型:T(类型)& -> 返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值
  • 检测是否自己给自己赋值
  • 返回*this :要复合连续赋值的含义
Date& operator=(const Date& d)
	{
		if (this != &d)
		{
			_year = d._year;
			_month = d._month;
			_day = d._day;
		}
		return *this;
	}
  1. 赋值运算符只能重载成类的成员函数不能重载成全局函数,否则会编译错误。
    在这里插入图片描述
    为什么呢?
    原因:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数

  2. 在类中,用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝(类似默认拷贝构造)。对于内置类型成员变量,是直接赋值的对于自定义类型成员变量,调用对应类的赋值运算符重载完成赋值
    在这里插入图片描述
    注意:如果类中未涉及到资源管理,赋值运算符是否实现都可以;一旦涉及到资源管理则必须要实现。因为默认的赋值重载实质上也是浅拷贝。

1.3 前置++和后置++重载

我们知道,无论是前置++还是后置++,其所用的运算符都是 ++。如果我们要对其重载,要如何分别实现前置++和后置++的重载呢?

C++规定:后置++重载时强制增加一个int类型的参数,但调用函数时该参数不用传递,编译器自动传递

这里也用Date类来举例:

//前置++重载:
//返回*this,也就是该类本身
Date& operator++()
{
	_day += 1;
	return *this;
}
//后置++重载:为了区分,强制加了一个int类型做区分
//后置++返回的是+1之前的值,所以要拷贝一个临时类来返回,而类本身要+1
//而temp是临时对象,因此只能以值的方式返回,不能返回引用
Date operator++(int)
{
	Date temp(*this);
	_day += 1;
	return temp;
}

此后所有的前置或后置类型符号的重载,都形似前置++和后置++的方式区分

2.日期类的实现

日期类的实现不仅是完整的实现其成员变量和成员函数,也要全套设计其运算符重载。

//Date.h
#pragma once
#include <iostream>
using namespace std;
class Date
{
public:
	//打印
	void Print()
	{
		cout << _year << "." << _month << "." << _day<<endl;
	}
	// 获取某年某月的天数
	//因为该成员函数要频繁调用,所以就放在类内
	int GetMonthDay(int year, int month)
	{
		
		static int a[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31 };
		int day = a[month];
		if (month == 2 && (year % 4 == 0 && year % 100 != 0 || year % 400 == 0))
		{
			day = 29;
		}
		return day;
	}
	// 全缺省的构造函数
	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);
	// >=运算符重载
	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;
};
//Date.c
#include "Date.h"
//构造
Date::Date(int year, int month, int day )
{
	this->_year = year;
	this->_month = month;
	this->_day = day;
}
//拷贝构造
Date::Date(const Date& d)
{
	this->_year = d._year;
	this->_month = d._month;
	this->_day = d._day;
}
//赋值拷贝
Date& Date::operator=(const Date& d)
{
	this->_year = d._year;
	this->_month = d._month;
	this->_day = d._day;
	return *this;
}
//析构函数
Date::~Date()
{
	_year = 0;
	_month = 0;
	_day = 0;
}
// +=重构
Date& Date::operator+=(int day)
{
	_day += day;
	while(_day > GetMonthDay(_year, _month))
	{
		_day -= GetMonthDay(_year, _month);//month = 12
		_month++;// month = 13
		if (_month > 12)
		{
			_month = 1;
			_year++;
		}
	}
	return *this;
}
// +重构
Date Date::operator+(int day)
{
	Date tmp = *this;
	tmp += day;
	return tmp;
}
// -=重构
Date& Date::operator-=(int day)
{
	_day -= day;
	while (_day <= 0)
	{
		 _month -= 1;
		if (_month == 0)
		{
			_month = 12;
			_year--;
		}
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}
// -重构
Date Date::operator-(int day)
{
	Date tmp = *this;
	tmp -= day;
	return tmp;
}
// 前置++重构
Date& Date::operator++()
{
	*this = *this + 1;
	return *this;
}
// 后置++重构
Date Date::operator++(int)
{
	Date tmp = *this;
	*this = *this + 1;
	return tmp;
}
// 前置--重构
Date& Date::operator--()
{
	*this = *this - 1;
	return *this;
}
// 后置--重构
Date Date::operator--(int)
{
	Date tmp = *this;
	*this = *this - 1;
	return tmp;
}
// ==重构
bool Date::operator==(const Date& d)
{
	return d._year == _year && d._month == _month && d._day == _day;
}
// >重构
bool Date::operator>(const Date& d)
{
	if (_year > d._year)
	{
		return true;
	}
	else if (_year == d._year && _month > d._month)
	{
		return true;
	}
	else if (_month == d._month && _day > d._day)
	{
		return true;
	}
	return false;
}
// <=重构
bool Date::operator<=(const Date& d)
{
	return !(*this > d);
}
// <重构
bool Date::operator<(const Date& d)
{
	if (_year < d._year)
	{
		return true;
	}
	else if (_year == d._year && _month < d._month)
	{
		return true;
	}
	else if (_month == d._month && _day < d._day)
	{
		return true;
	}
	return false;
}
// >=重构
bool Date::operator>=(const Date& d)
{
	return !(*this < d);
}
// !=重构
bool Date::operator!=(const Date& d)
{
	return !(*this == d);
}
// 日期-日期 返回天数
int Date::operator-(const Date& d)
{
	Date max = *this;
	Date min = d;
	int flag = -1;
	if (max < min)
	{
		max = d;
		min = *this;
		flag = 1;
	}
	int n = 0;
	while (max != min)
	{
		max--;
		n++;
	}
	return n * flag;
}

3. const成员函数

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

class Date
{
public:
	//const修饰成员函数
	//    该放在这里↓ 
	void fun() const
	{

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

在这里插入图片描述

4 取地址及const取地址操作符重载

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

class Date
{
public:
	//返回this指针也就是是Date类的地址
	Date* operator&()
	{
		return this;
	}
	//为了防止权限的放大,也会重载一个返回值是const修饰的指针
	const Date* operator&()const
	{
		return this;
	}
private:
	int _year; // 年
	int _month; // 月
	int _day; // 日
};

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

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

相关文章

双非一战逆天改命,上岸Top3!

这个系列会邀请上岸学长学姐进行经验分享~今天经验分享的同学同样是小马哥上海交大819的全程班学员&#xff0c;双非逆袭上岸&#xff0c;非常厉害&#xff01; 01-前言 个人介绍&#xff1a;本人就读于江苏某双非&#xff0c;绩点3.2&#xff0c;本科期间仅校赛级别奖项。四…

JavaSE内部类

内部类概述 1.内部类的基础 内部类的分类&#xff1a;实例化内部类&#xff0c;静态内部类&#xff0c;局部内部类和匿名内部类 public class OutClass {// 成员位置定义&#xff1a;未被static修饰 --->实例内部类public class InnerClass1{}// 成员位置定义&#xff1a;被…

公园景区伴随音乐系统-公园景区数字IP广播伴随音乐系统建设指南

公园景区伴随音乐系统-公园景区数字IP广播伴随音乐系统建设指南 由北京海特伟业任洪卓发布于2024年4月23日 随着“互联网”被提升为国家战略&#xff0c;传统行业与互联网的深度融合正在如火如荼地展开。在这一大背景下&#xff0c;海特伟业紧跟时代步伐&#xff0c;凭借其深厚…

如何在PostgreSQL中跟踪和分析查询日志,以便于排查性能瓶颈?

文章目录 启用查询日志分析查询日志1. 查找执行时间长的查询2. 分析资源消耗3. 使用pgBadger分析4. 优化查询 示例代码结论 在PostgreSQL中&#xff0c;跟踪和分析查询日志是排查性能瓶颈的重要步骤。通过查看和分析查询日志&#xff0c;我们可以了解哪些查询在执行时遇到了问题…

17.Nacos与Eureka区别

Nacos会将服务的提供者分为临时实例和非临时实例。默认为临时实例。 临时实例跟eureka一样&#xff0c;会向注册中心报告心跳监测自己是否还活着。如果不正常了nacos会剔除临时实例。&#xff08;捡来的孩子&#xff09; 非临时实例&#xff0c;nacos会主动询问服务提供者是否…

232 基于matlab的MIMO雷达模型下一种子空间谱估计方法

基于matlab的MIMO雷达模型下一种子空间谱估计方法&#xff0c;采用过估计的方法&#xff0c;避免了信源数估计的问题&#xff0c;对数据协方差矩阵进行变换&#xff0c;构造信号子空间投影矩阵和噪声子空间投影矩阵&#xff0c;不需要像经典的MUSIC一样对其进行特征分解&#x…

BBS前后端混合项目--03

展示 static/bootstrp # bootstrap.min.css /*!* Bootstrap v3.4.1 (https://getbootstrap.com/)* Copyright 2011-2019 Twitter, Inc.* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)*//*! normalize.css v3.0.3 | MIT License | github.com/n…

Python练习03

题目 解题思路 Demo58 通过字符串切片来进行反转操作 def _reverse():"""这是一个反转整数的函数"""num input("请输入想要反转的整数")print(num[::-1]) 运行结果 Demo61 首先制作一个判断边长的函数&#xff0c;通过三角形两边…

vue3项目 使用 element-plus 中 el-collapse 折叠面板

最近接触拉了一个项目&#xff0c;使用到 element-plus 中 el-collapse 折叠面板&#xff0c;发现在使用中利用高官网多多少少的会出现问题。 &#xff08;1.直接默认一个展开值&#xff0c;发现时显时不显 2 . 数据渲染问题&#xff0c;接口请求了&#xff0c;页面数据不更新 …

捕捉信号的处理

文章目录 信号捕捉 信号捕捉 信号捕捉是进程从内核态返回用户态时会对信号进行检测处理。 如果信号的处理动作是用户自定义函数,在信号递达时就调用这个函数,这称为捕捉信号。由于信号处理函数的代码是在用户空间的,处理过程比较复杂,举例如下: 用户程序注册了SIGQUIT信号的处…

linux——cron定时任务

cron定时任务配置文件中可以查看一些信息 crontab就是在提交以及管理需要周期性执行的任务 定时任务具体实现需要使用crontab命令编辑对应定时任务文件 这里执行定时任务&#xff0c;每分钟创建一个文件1.txt

jvm中的垃圾回收器

Jvm中的垃圾回收器 在jvm中&#xff0c;实现了多种垃圾收集器&#xff0c; 包括&#xff1a; 1.串行垃圾收集器 2.并行垃圾收集器 3.CMS&#xff08;并发&#xff09;垃圾收集器 4.G1垃圾收集器 1.串行垃圾回收器 效率低&#xff0c;使用较少 2.并行垃圾回收器 3.并发垃圾回…

mysql download 2024

好久没在官网下载 mysql server 安装包。今天想下载发现&#xff1a; 我访问mysql官网的速度好慢啊。mysql server 的下载页面在哪里啊&#xff0c;一下两下找不到。 最后&#xff0c;慢慢悠悠终于找到了下载页面&#xff0c;如下&#xff1a; https://dev.mysql.com/downlo…

3 命名实体识别调优化

能走到这里说明你对模型微调有了一个基本的认识。那么开始一段命名实体的任务过程&#xff0c;下面使用huggingface官网的数据。 1 准备模型 下面的模型自己选择一个吧&#xff0c;我的内存太第一个模型跑不了。 https://huggingface.co/ckiplab/bert-base-chinese-ner/tree…

医学访问学者专栏—研究领域及工作内容

在国外访问学者申请中&#xff0c;医学领域的研究、教学及从业人员占有相当大的比例&#xff0c;这些医学访问学者的研究领域及工作内容都有哪些&#xff1f;本文知识人网小编就相关问题进行详细阐述&#xff0c;并附带案例说明。 一、在国外做医学访问学者可以从事哪些工作&am…

Win10 打开有些软件主界面会白屏不显示,其他软件都正常

环境&#xff1a; Win10专业版 英伟达4070 显卡 问题描述&#xff1a; Win10 打开有些软件主界面会白屏不显示,打开远程协助软件AIRMdesk,白色&#xff0c;其他软件都正常 解决方案&#xff1a; 网上说电脑没有接显示器独立显卡的关系导致 我是只有一台主机&#xff0c;没…

appium相关的知识

>adb shell dumpsys window | findstr mCurrentFocus adb devices # 实例化字典 desired_caps = dict() desired_caps[platformName] = Android desired_caps[platformVersion] = 9 # devices desired_caps[deviceName] = emulator-5554 # 包名 desired_caps[appPackage] …

DRF 查询(排序、过滤、分页)

查询(排序、过滤、分页) 【0】准备 &#xff08;1&#xff09;Q查询 详细内容可见&#xff1a;Django模型层-CSDN博客Django 的 Q 对象提供了一种在数据库查询中构造复杂查询的方法。当你想在单个查询中组合多个过滤条件&#xff0c;并且这些条件之间不仅仅是简单的 AND 关系…

MySQL8.0.36-社区版:二进制日志(4)

什么是二进制日志&#xff08;binlog&#xff09;&#xff1a;记录了所有的ddl和dml语句&#xff0c;但是不包括查询类的 二进制日志的作用&#xff1a;1.灾难恢复&#xff0c;2.mysql主从复制 查看二进制日志状态 show variables like %log_bin%; 在mysql8中默认是开启的 | l…

TLV61048非同步升压BOOST转换器输入电压2.6-5.5V输出电流4A输出电压最高15V

推荐原因&#xff1a; 输入电压较低&#xff0c;输出电流可达3.5A SOT23-6封装 批量价格约0.70元 TLV61048引脚 TLV61048引脚功能 7 详细说明 7.1 概述 TLV61048是一款非同步升压转换器&#xff0c;支持高达 15 V 的输出电压和输入范围从 2.61 V 到 5.5 V。该TLV61048集成了…