【C++】类和对象(中)--下篇

在这里插入图片描述
个人主页~
类和对象上
类和对象中-上篇


类和对象

  • 五、赋值运算符重载
    • 1、运算符重载
    • 2、赋值运算符重载
    • 3、前置++和后置++重载
  • 六、const成员
  • 七、日期类的实现
    • Date.h
    • Date.cpp
    • test.cpp
      • test1测试结果
      • test2测试结果
      • test3测试结果
      • test4测试结果
      • test5测试结果
      • test6测试结果
      • test7测试结果
  • 八、关于取地址和const取地址操作符重载

五、赋值运算符重载

1、运算符重载

运算符重载是具有特殊函数名的函数,是C++为了增强代码可读性而引入的

operator sign(parameter);

operator为关键字,sign就是需要重载的运算符符号,parameter为参数(可以为多个)

注意事项:

不能通过连接其他符号来创建新的操作符

重载操作符至少有一个类类型参数

用于内置类型之间的运算符含义不改变,编译器会自动检测使用运算符的类型是什么,从而选择是否改变运算符含义

类成员函数重载时有一个隐藏的参数this

不能重载的五个运算符
.*
::
sizeof
?:
.

重载一个==

//……全局
bool operator==(const Date& d1, const Date& d2)
{
    return d1._year == d2._year
   && d1._month == d2._month
        && d1._day == d2._day;
}
//……

但定义一个全局函数需要成员函数公有,所以我们直接定义在类内,保证其封装性

//……类内
bool operator==(const Date& d2)
{
	return _year == d2._year
		&& _month == d2._month
		&& _day == d2._day;
}
//……

2、赋值运算符重载

(1)格式
参数类型 const name& 引用传参

返回值类型 name& 返回引用

检测是否自己给自己赋值

返回*this

(2)赋值运算符的重载
赋值运算符只能重载成类的成员函数不能重载成全局函数

赋值运算符如果不显式实现,编译器会生成一个默认的,此时再在外边实现一个全局的赋值运算符重载,就会发生冲突

class Date
{
public:
	Date(int year, int month, int day)
	{
		_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;
};

(3)用户没有显式实现时,编译器会生成一个默认赋值运算符重载,然后值拷贝,内置成员直接赋值,自定义成员需要调用对应类的赋值运算符重载完成赋值

(4)有了值拷贝我们就一定要说说深拷贝,在Date类这样的类中不需要我们自己实现,而在Stack这样的类中就需要显式实现,进行资源管理

拿出我们的老演员栈:

typedef int DataType;
class Stack
{
public:
	Stack(size_t capacity = 10)
	{
		arr = (DataType*)malloc(capacity * sizeof(DataType));
		if (nullptr == arr)
		{
			perror("malloc申请空间失败");
			return;
		}
		size = 0;
		capacity = capacity;
	}
	void Push(const DataType& data)
	{
		// CheckCapacity();
		arr[size] = data;
		size++;
	}
	~Stack()
	{
		if (arr)
		{
			free(arr);
			arr = nullptr;
			capacity = 0;
			size = 0;
		}
	}
private:
	DataType* arr;
	size_t size;
	size_t capacity;
};
int main()
{
	Stack s1;
	s1.Push(1);
	s1.Push(2);
	Stack s2;
	s2 = s1;
	return 0;
}

在这里插入图片描述
调试后发现又是析构函数这里出了问题,原因同拷贝构造函数:因为编译器自动生成的拷贝构造函数是值拷贝,所以在生成s2时,s2中的指针a指向的数组与s1中的指针指向的数组相同,在程序结束时,调用析构函数释放了s2,对应的这块数组空间也被释放,然后调用析构函数释放s1,已经被释放的空间不能被再次释放,所以出现了这样的错误,所以我们需要自己显式定义一个拷贝构造函数

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

我们先来复习一下前置++和后置++的区别,在仅自加时也就是在n++为一条语句时没有区别,在赋值时,前置++是先+1后赋值,后置++是先赋值再+1

如果我们想要++重载,那么就是定义operator++,分不出为前置还是后置,所以我们规定operator++为前置++operator++(int)为后置++

class Date
{
public:
	Date(int year = 1970, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	Date& operator++()
	{
		*this += 1;
		return *this;
	}
	Date operator++(int)
	{
		Date tmp(*this);
		*this += 1;
		return tmp;
	}
	//所以后置++会使用空间拷贝,效率比前置++低
	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};

int main()
{
	Date d;
	Date d1(2000,1,1);
	d = d1++;
	d.Print();
	d1.Print();
	d = ++d1;
	d.Print();
	d1.Print();
	return 0;
}

在这里插入图片描述

六、const成员

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

因为参数为隐藏的,所以我们的方法如下:

void Date::Print() const
{
	cout << _year << "/" << _month << "/" << _day << endl;
}

相当于

void Date::Print(const Date* this) 
{
	cout << _year << "/" << _month << "/" << _day << endl;
}

注意:

const对象不能调用非const成员函数

非const对象能调用const成员函数

const成员函数内不能调用其他非const成员函数

非const成员函数内能调用其他const成员函数

七、日期类的实现

Date.h

#pragma once
#include <iostream>
using namespace std;

class Date
{
public:
	int GetMonthDay(int year, int month);

	Date(int year = 1970, int month = 1, int day = 1);
	Date(const Date& d);
	~Date();

	Date& operator=(const Date& d);
	Date& operator+=(int day);
	Date& operator-=(int day);
	Date& operator++();
	Date operator++(int);
	Date& operator--();
	Date operator--(int);
	Date operator+(int day);
	Date operator-(int day);

	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);

	void Print() const;
private:
	int _year;
	int _month;
	int _day;
};

Date.cpp

#define _CRT_SECURE_NO_WARNINGS

#include "Date.h"

int Date::GetMonthDay(int year, int month)
{
	const static int days[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 days[month];
}

Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;
	if (month < 1 || month > 12
		|| day < 1 || day > GetMonthDay(year, month))
	{
		cout << "非法日期" << endl;
		exit(-1);
	}
}

Date::Date(const Date& d)
{
	_year = d._year;
	_month = d._month;
	_day = d._day;
}

Date::~Date()
{
	_year = _month = _day = 0;
}
//日期类的析构函数其实没必要写
Date& Date::operator=(const Date& d)
{
	if(this != &d)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	return *this;
}

Date& Date::operator+=(int day)
{
	if (day < 0)
	{
		return *this -= (-day);
	}//复用-=

	_day += day;
	while (_day > GetMonthDay(_year, _month))
	{
		_day -= GetMonthDay(_year, _month);
		++_month;

		if (_month == 13)
		{
			++_year;
			_month = 1;
		}
	}
	return *this;
}

Date& Date::operator-=(int day)
{
	if (day < 0)
	{
		return *this += (-day);
	}//复用+=

	_day -= day;

	while (_day <= 0)
	{
		--_month;
		if (_month == 0)
		{
			--_year;
			_month = 12;
		}

		_day += GetMonthDay(_year, _month);
	}

	return *this;
}

Date& Date::operator++()
{
	*this += 1;
	return *this;
}

Date Date::operator++(int)
{
	Date tmp(*this);

	*this += 1;

	return tmp;
}

Date& Date::operator--()
{
	*this -= 1;
	return *this;
}

Date Date::operator--(int)
{
	Date tmp(*this);

	*this -= 1;

	return tmp;
}

Date Date::operator+(int day)
{
	Date tmp(*this);

	tmp += day;

	return tmp;
}

Date Date::operator-(int day)
{
	Date tmp(*this);

	tmp -= day;

	return tmp;
}

bool Date::operator==(const Date& d)
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._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 (_year == d._year && _month == d._month && _day < d._day)
	{
		return true;
	}
	else
	{
		return false;
	}
}

// d1 <= d2
bool Date::operator<=(const Date& d)
{
	return *this < d || *this == d;
}

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

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

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

int Date::operator-(const Date& d)
{
//假设左大右小,此时标识符flag为1
	Date max = *this;
	Date min = d;
	int flag = 1;
//如果左小右大,则置换后置标识符flag为-1
	if (*this < d)
	{
		max = d;
		min = *this;
		flag = -1;
	}
//算出大的与小的之间的天数
	int n = 0;
	while (min != max)
	{
		++min;
		++n;
	}
//返回与标识符flag的乘积
	return n * flag;
}

void Date::Print() const
{
	cout << _year << "/" << _month << "/" << _day << endl;
}

test.cpp

#define _CRT_SECURE_NO_WARNINGS

#include "Date.h"
//初始化
void test1()
{
	Date d1(2000, 1, 1);
	d1.Print();
	Date d2;
	d2.Print();
	Date d3 = Date(d1);
	d3.Print();
}
//++
void test2()
{
	Date d1(2001, 2, 28);
	Date d2 = d1++;
	Date d3 = ++d1;
}
//+ -
void test3()
{
	Date d1(2000, 1, 1);
	Date d2 = d1 + 20000;
	Date d3 = d1 - 20000;
}
//--
void test4()
{
	Date d1(2000, 3, 1);
	Date d2 = d1--;
	Date d3 = --d1;
}
//+= -=
void test5()
{
	Date d1(2000, 1, 1);
	d1 += 20000;
	Date d2;
	d2 -= 20000;
}
//日期-日期
void test6()
{
	Date d1(2000, 1, 1);
	Date d2;
	int a = d1 - d2;
}
//=
void test7()
{
	Date d1(2000, 1, 1);
	Date d2;
	d2 = d1;
}
int main()
{
	//test1();
	//test2();
	//test3();
	//test4();
	//test5();
	//test6();
	//test7();
	return 0;
}

test1测试结果

在这里插入图片描述
构造和拷贝构造函数正常

test2测试结果

在这里插入图片描述
在这里插入图片描述
前置后置++都正常

test3测试结果

在这里插入图片描述

在这里插入图片描述

+、 - 不改变原来的值,正常

test4测试结果

在这里插入图片描述

在这里插入图片描述
前置后置- -正常

test5测试结果

在这里插入图片描述
-= +=改变原来的数,正常

test6测试结果

在这里插入图片描述
日期减日期为整数正常

test7测试结果

在这里插入图片描述

=赋值正常

全部正常

八、关于取地址和const取地址操作符重载

&
const …… &
这两个一般不用重新定义,编译器会默认生成,如果有别的用途,可以显式定义重载


今日分享结束~

在这里插入图片描述

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

如何在Excel中对一个或多个条件求和?

在Excel中&#xff0c;基于一个或多个条件的求和值是我们大多数人的常见任务&#xff0c;SUMIF函数可以帮助我们根据一个条件快速求和&#xff0c;而SUMIFS函数可以帮助我们对多个条件求和。 本文&#xff0c;我将描述如何在Excel中对一个或多个条件求和&#xff1f; 在Excel中…

R语言学习笔记2-RRStudio环境配置(Windows版)

R语言学习笔记2-R&RStudio环境配置&#xff08;Windows版&#xff09; 安装 R安装RStudio修改默认工作目录修改镜像验证镜像源修改文件编码 环境测试 安装 R R下载地址&#xff1a; https://mirrors.tuna.tsinghua.edu.cn/CRAN/bin/windows/base/ 点击下载链接并运行安装程…

《网络安全和信息化》是什么级别的期刊?是正规期刊吗?能评职称吗?

​问题解答 问&#xff1a;《网络安全和信息化》是不是核心期刊&#xff1f; 答&#xff1a;不是&#xff0c;是知网收录的正规学术期刊。 问&#xff1a;《网络安全和信息化》级别&#xff1f; 答&#xff1a;国家级。主管单位&#xff1a;工业和信息化部 主办单位&#…

PostgreSQL主从同步

目录 一、主从复制原理 二、配置主数据库 2.1 创建同步账号 2.2 配置同步账号访问控制 2.3 设置同步参数 3.4 重启主数据库 三、配置从数据库 3.1 停止从库 3.2 清空从库数据文件 3.3 拉取主库数据文件 3.4 配置从库同步参数 3.5 启动从库 四、测试主从 4.1在主库…

家用美容仪维修

美容仪行业是一个随着消费者对外貌和健康关注度不断提高而快速发展的行业。以下是对美容仪行业的详细分析&#xff1a; 一、行业概况 美容仪是一种根据人体生理机能进行调节改善身体和面部的机器&#xff0c;具有美白、嫩肤、祛斑、祛皱、脱毛、减肥等多种功能。随着科技的发…

Mac可以玩Steam吗?苹果电脑可以玩的单机游戏有哪些?

Mac可以玩Steam吗 关于Mac是否能够运行Steam这一问题&#xff0c;答案是肯定的。Steam平台已经支持Mac操作系统&#xff0c;玩家可以通过Steam在Mac上购买、下载和游玩各种优秀的游戏作品。不过&#xff0c;需要注意的是&#xff0c;并非所有的Steam游戏都有Mac版&#xff0c;…

JavaScript 中的面向对象编程--->构造函数--->原型对象与原型链,由浅入深详细讲解!

前言&#xff1a;哈喽&#xff0c;大家好&#xff0c;我是前端菜鸟的自我修养&#xff01;今天给大家分享JavaScript 中的面向对象编程--->构造函数--->原型对象与原型链&#xff0c;由浅入深详细讲解&#xff01;并提供具体代码帮助大家深入理解&#xff0c;彻底掌握&am…

去水印小程序源码修复版-前端后端内置接口+第三方接口

去水印小程序源码&#xff0c;前端后端&#xff0c;内置接口第三方接口&#xff0c; 修复数据库账号密码错误问题&#xff0c;内置接口支持替换第三方接口&#xff0c; 文件挺全的&#xff0c;可以添加流量主代码&#xff0c;搭建需要准备一台服务器&#xff0c;备案域名和http…

【Arduino】XIAOFEIYU(TM)实验ESP32使用DS18B20数字温度传感器模块(图文)

DS18B20 虽然具有测温系统简单、测温精度高、连接方便、占用口线少等优点。今天XIAOFEIYU(TM)就来实验一下使用ESP32连接DS18B20数字温度传感器模块。 DS18B20数字温度传感器模块一共有3个针脚&#xff0c;正负极加一个out数据接口。 连接传感器和ESP32组成测试电路&#xff1a…

R包:蛋白质组学质控评估PTXQC包

介绍 PTXQC包是2016年发表在J Proteome Res期刊上的R包&#xff0c;它主要是对MaxQuant输出结果进行提取处理从而获得评估蛋白质质量结果。 安装 从github安装&#xff0c;安装过程会自动构建tutorial。 devtools::install_github("cbielow/PTXQC", build_vignet…

Qt篇——QLabel固定尺寸的情况下让字体大小自适应并自动换行以完整显示

当文字较少时&#xff0c;默认字体大小为16&#xff1b;当文字内容较多时&#xff0c;自动换行并缩小字体。 举例&#xff1a; 字体较少时 字体较多时 思路&#xff1a; 设置自动换行属性 setWordWrap&#xff1b;通过QFontMetrics计算文字字体要多大、显示多少行才不会超过…

利用亚马逊云科技云原生Serverless代码托管服务开发OpenAI ChatGPT-4o应用

今天小李哥继续介绍国际上主流云计算平台亚马逊云科技AWS上的热门生成式AI应用开发架构。上次小李哥分享​了利用谷歌云serverless代码托管服务Cloud Functions构建Gemini Pro API​&#xff0c;这次我将介绍如何利用亚马逊的云原生服务Lambda调用OpenAI的最新模型ChatGPT 4o。…

MySQL之表的约束(上)

目录 空属性(NULL) 实例建表 插入操作 默认值(default) 建表 插入操作 NULL与default的结合 列描述 建表 zerofill 建表 插入操作 主键 建表 插入 主键的增加与去掉 去掉 增加 复合主键 插入的影响 真正约束字段的是数据类型&#xff0c;但是数据类型约束很单一&a…

burpsuite官方靶场之命令注入

1.简单的命令注入 1.1 达成目标 成功执行whoami查看当前用户的名字。 1.2 攻击步骤 观察该靶场的页面&#xff0c;发现这是一个展示其商品信息的页面&#xff0c;点击view details可以展示每个商品的详情。 来到一个商品的详情页&#xff0c;发现画框部分是检查商品库存的功…

合合信息大模型“加速器”重磅上线

大模型技术的发展和应用&#xff0c;预示着更加智能化、个性化未来的到来。如果将大模型比喻为正在疾驰的科技列车&#xff0c;语料便是珍贵的“燃料”。本次世界人工智能大会期间&#xff0c;合合信息为大模型打造的“加速器”解决方案备受关注。 在大模型训练的上游阶段&…

CSS 后代选择器正确写法 爸爸儿子之间有代沟

CSS 后代选择器正确写法 爸爸儿子之间有代沟 example&#xff1a; > <body> > <div class"outer"> > <span class"inner"></span> > </div> > </body> > <head> > <style>…

如何在浏览器控制台Console中引入外部 JS

想要在某个网页执行一些脚本&#xff0c;却发现某个工具类&#xff0c;如 ajax 请求的 axios 该网页没有引入&#xff0c;或者引入了但控制台却访问不到&#xff0c;这时要怎么办呢&#xff1f; 只需要控制台执行如下代码就好了 var script document.createElement(script);…

Postman使用指南①网页版使用

postman官网地址&#xff1a;Postman API Platform 进入后点击右上角免费注册&#xff0c;注册后登录 登录之后即可在网页使用&#xff0c;无需下载

C语言学习笔记[22]:分支语句switch

switch语句 switch语句也是一种分支语句&#xff0c;常用于多分支的情况 switch语句的语法形式是&#xff1a; switch(整型表达式) {语句项; }而语句项是什么呢&#xff1f; case 整型常量表达式:语句; switch语句中的break 对于case 语句来说&#xff0c;我们day输入的多…

电动卡丁车语音芯片方案选型:让驾驶体验更智能、更安全

在追求速度与激情的电动卡丁车领域&#xff0c;每一次升级都意味着更加极致的驾驶体验。而今天&#xff0c;我们要介绍的&#xff0c;正是一款能够显著提升电动卡丁车智能化与安全性的语音芯片方案——为您的爱车增添一份独特的魅力与安全保障。 智能化升级&#xff0c;从“听…