【C++】学习笔记——类和对象_4

news2024/9/25 8:16:36

文章目录

  • 二、类和对象
    • 13.运算符重载
      • 赋值运算符重载
    • 14. 日期类的实现
      • Date.h头文件
      • Date.cpp源文件
      • test.cpp源文件
  • 未完待续


二、类和对象

13.运算符重载

赋值运算符重载

我们之前学了一个拷贝构造函数,本质上就是创建一个对象,该对象初始化为一个已经存在的对象的数据。

// 拷贝构造
Date d1(d2);

而赋值运算符重载则是重载一个赋值运算符 “=” ,然后让两个已经存在的对象,一个拷贝赋值给另一个。

// 赋值运算符重载
d1 = d2;

普通赋值运算符是支持连续赋值的,所以我们重载后的也需要连续赋值,即函数需要返回左值。
赋值运算符的实现:

#include<iostream>
using namespace std;

class Date
{
public:
	Date(int year = 1111, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	~Date() {}

	void Print()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

	// 拷贝构造函数
	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;
};

int main()
{
	Date d1(2222, 2, 2);
	Date d2(d1);
	d1 = d2;
	return 0;
}

赋值运算符重载函数也是6个默认的成员函数之一,所以我们不写编译器也会自动生成。它跟拷贝构造函数很相似,对内置类型进行浅拷贝处理,对自定义类型去调用它的赋值运算符重载函数。由于也是浅拷贝,所以涉及到堆上的空间开辟时,不能使用编译器自动生成的赋值运算符重载函数。

14. 日期类的实现

这个日期类的实现将会将之前学的所有知识进行融合。我们来进行标准的声明和定义分离。

Date.h头文件

头文件里只包括声明

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;

class Date
{
public:
	// 构造函数的声明
	Date(int year = 1111, int month = 1, int day = 1);

	// 重载运算符的声明
	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);

	// 日期加天数
	Date& operator+=(int day);
	Date operator+(int day);
	Date operator-(int day);
	Date& operator-=(int day);

	// ++d1
	Date& operator++();
	// d1++  为了跟前置++区分,后置++强行增加了一个int形参,构成重载区分
	Date operator++(int);
	Date& operator--();
	Date operator--(int);

	// 日期减日期
	int operator-(const Date& d);

	int GetMonthDay(int year, int month)
	{
		// 断言月份错误
		assert(month >= 1 && month <= 12);

		// 静态变量只初始化一次
		static int monthDays[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 monthDays[month];
	}

	// 打印日期的声明
	void Print();
	
private:
	int _year;
	int _month;
	int _day;
};

Date.cpp源文件

这个文件里是各个函数的定义。

#include"Date.h"

// 构造函数的定义
Date::Date(int year, int month, int day)
{
	_year = year;
	_month = month;
	_day = day;
}

// 重载运算符的定义
bool Date::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)
		{
			return _day < d._day;
		}
	}
	return false;
}

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 _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

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

Date& 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 Date::operator+(int day)
{
	// 拷贝构造,避免修改原来的日期
	Date tmp(*this);
	// 使用重载后的+=
	tmp += day;

	// 局部对象不能引用返回
	return tmp;
}

Date Date::operator-(int day)
{
	// tmp是刚创建的对象,所以这是拷贝构造而不是赋值
	Date tmp = *this;
	tmp -= day;

	return tmp;
}

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

	return *this;
}

// ++d1
Date& Date::operator++()
{
	*this += 1;

	return *this;
}

// d1++
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;
}

int Date::operator-(const Date& d)
{
	int flag = 1;
	Date max = *this;
	Date min = d;
	if (*this < d)
	{
		flag = -1;
		max = d;
		min = *this;
	}
	int n = 0;
	while (max != min)
	{
		++min;
		++n;
	}

	return flag * n;
}

// 打印日期的定义
void Date::Print()
{
	cout << _year << "-" << _month << "-" << _day << endl;
}

test.cpp源文件

#include"Date.h"

int main()
{
	Date d1(2222, 2, 2);
	d1.Print();
	Date d2 = d1 + 10;
	d2.Print();
	cout << (d1 > d2) << endl;
	Date d3;
	d3.Print();
	d3 += 10000;
	d3.Print();
	--d3;
	d3.Print();
	cout << (d1 - d3) << endl;
	return 0;
}

结果:
在这里插入图片描述


未完待续

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

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

相关文章

【智能算法】寄生捕食算法(PPA)原理及实现

目录 1.背景2.算法原理2.1算法思想2.2算法过程 3.结果展示4.参考文献 1.背景 2020年&#xff0c;AAA Mohamed等人受到自然界乌鸦-布谷鸟-猫寄生系统启发&#xff0c;提出了寄生捕食算法&#xff08;Parasitism – Predation Algorithm, PPA&#xff09;。 2.算法原理 2.1算法…

负采样重要吗?它的理论与应用综述

Does Negative Sampling Matter? A Review with Insights into its Theory and Applications 负采样重要吗&#xff1f;它的理论与应用综述 Does Negative Sampling Matter? A Review with Insights into its Theory and Applications Zhen Yang, Ming Ding, Tinglin Huang,…

7-23 币值转换 【C++】

有点颠的一个测试点&#xff0c;记录一下 测试点二&#xff0c;是看了一些AC代码才写出来的&#xff0c;至于原理我也不知道&#xff0c;就当多见识一点题目测试点的可能性吧 #include<iostream> #include<cstring> using namespace std; int main() {string a;ch…

vue-Router 路由(常量路由)

1、安装 pnpm i vue-router 2、新建文件&#xff1a;src/routes.ts import { RouteRecordRaw } from vue-routerexport const constantRoute: RouteRecordRaw[] [{//path: /,redirect: /login,},{//path: /login,component: () > import(/views/Login/index.vue),name…

进程及进程地址空间

进程理解 概念&#xff1a;进程是程序的一个执行实例&#xff0c;其实启动一个程序&#xff08;静态&#xff09;本质就是启动了一个进程&#xff08;动态&#xff09;&#xff0c;进程具有独立性。 用户角度&#xff1a;进程代码数据内核数据结构&#xff08;PCB结构体页表操…

mysql的DDL语言和DML语言

DDL语言&#xff1a; 操作数据库&#xff0c;表等&#xff08;创建&#xff0c;删除&#xff0c;修改&#xff09;&#xff1b; 操作数据库 1&#xff1a;查询 show databases 2:创建 创建数据库 create database 数据库名称 创建数据库&#xff0c;如果不存在就创建 crea…

【Qcom Camera】DumpDebugInfo分析

DumpDebugInfo&#xff1a; DumpDebugInfo主要包括Session::DumpDebugInfo、Pipeline::Dumpdebuginfo、Node::Dumpdebuginfo、DRQ::Dumpdebuginfo、Usecase::DumpDebugInfo log&#xff1a;Hit SOF threshold of [xx] consecutive frames CamX: [ERROR][CORE ] camxpip…

P8837 [传智杯 #3 决赛] 商店(贪心加双指针)

题目背景 思路解析:很经典的贪心问题,把物品按照从便宜到贵的顺序排好序,然后按照富贵程度排人,直接暴力会tle所以这里采用双指针. #include<iostream> #include<algorithm> #include<cstring> #include<cmath> #include<string> using namesp…

AI-数学-高中-39空间向量-2空间向量法(法向量)

原作者视频&#xff1a;【空间向量】【一数辞典】2空间向量法&#xff08;重要&#xff09;_哔哩哔哩_bilibili 法向量&#xff08;高中阶段所有与面的关系&#xff0c;都可以通过法向量去证明和解答&#xff09;&#xff1a; 是空间解析几何的一个概念&#xff0c;垂直于平面…

Java转go,我用了12小时,10小时在解决环境问题

Part1 问题背景 作为一个资深的Java开发者&#xff0c;我深知面向对象的高级语言&#xff0c;语法是不用学的。需要的时候搜索就可以了&#xff0c;甚至可以用ChatGPT来写。 之前我做一个安全多因素校验服务。因为是临时服务&#xff0c;扩展性上基本没有要求&#xff0c;为了快…

AI检索增强生成引擎-RAGFlow-深度理解知识文档,提取真知灼见

&#x1f4a1; RAGFlow 是什么&#xff1f; RAGFlow是一款基于深度文档理解构建的开源RAG&#xff08;Retrieval-Augmented Generation&#xff09;引擎。RAGFlow个人可以为各种规模的企业及提供一套专业的RAG工作流程&#xff0c;结合针对用户群体的大语言模型&#xff08;LL…

玩转 AIGC!使用 SD-WebUI 实现从文本到图像转换

节前&#xff0c;我们组织了一场算法岗技术&面试讨论会&#xff0c;邀请了一些互联网大厂朋友、参加社招和校招面试的同学&#xff0c;针对算法岗技术趋势、大模型落地项目经验分享、新手如何入门算法岗、该如何准备、面试常考点分享等热门话题进行了深入的讨论。 基于大家…

500道Python毕业设计题目推荐,附源码

博主介绍&#xff1a;✌程序员徐师兄、7年大厂程序员经历。全网粉丝12w、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专栏推荐订阅&#x1f447;…

Quick Service Setup(快速服务设置)

Quick Service Setup界面使用户能够使用最少的参数快速配置和编辑简单的应用程序服务。Alteon自动为虚拟服务创建所需的对象(虚拟服务器、服务器组、真实服务器、SSL策略、FastView策略等)。通过快速服务设置&#xff0c;您可以配置HTTP, HTTPS&#xff0c;基本slb(第4层TCP或U…

BootstrapAdmin Net7:基于RBAC的后台管理框架,实现精细化权限管理与多站点单点登录

BootstrapAdmin Net7&#xff1a;基于RBAC的后台管理框架,实现精细化权限管理与多站点单点登录 摘要 随着企业信息化建设的不断深入&#xff0c;后台管理系统在企业运营中扮演着越来越重要的角色。本文介绍了一款基于RBAC&#xff08;Role-Based Access Control&#xff09;的…

海外媒体如何发布软文通稿

大舍传媒-带您了解海外发布新潮流 随着全球化的不断深入&#xff0c;越来越多的中国企业开始关注海外市场。为了在国际舞台上树立品牌形象&#xff0c;企业纷纷寻求与海外媒体合作&#xff0c;通过发布软文通稿的方式&#xff0c;传递正面信息&#xff0c;提升品牌知名度。作为…

算法导论 总结索引 | 第三部分 第十一章:散列表

1、动态集合结构&#xff0c;它至少要支持 INSERT、SEARCH 和 DELETE字典操作 散列表 是实现字典操作的 一种有效的数据结构。尽管 最坏情况下&#xff0c;散列表中 查找一个元素的时间 与链表中 查找的时间相同&#xff0c;达到了 Θ(n)。在实际应用中&#xff0c;散列表的性…

制造业降本,为什么要关注流程挖掘?

不同于传统制造,智能制造企业数字化启动早、程度高,却总因“集成陷阱”无法摆脱业财协同差的问题。长期的“治标不治本”,导致超支、违规、资金分配不合理等问题仍藏于每个任务流中,甚至直接影响营运现金流的健康度。 《从流程挖掘到降本增收——智能制造企业支出洞察》报告,基…

实验2 NFS部署和配置

一、实训目的 1.了解NFS基本概念 2.实现NFS的配置和部署 二、实训准备 1.准备一台能够安装OpenStack的实验用计算机&#xff0c;建议使用VMware虚拟机。 2.该计算机应安装CentOS 7&#xff0c;建议采用CentOS 7.8版本。 3.准备两台虚拟机机&#xff08;客户机和服务器机&…

NTLM认证

文章目录 1.概念(1) 本地认证(2) SAM(3) NTLM Hash(4) NTLM 和 NTLM Hash(5) NTLM v2 1.概念 (1) 本地认证 Windows不存储用户的明文密码&#xff0c;它会将用户的明文密码经过加密后存储在 SAM (Security Account Manager Database&#xff0c;安全账号管理数据库)中。 (2)…