【C++】类和对象 ——中

news2024/9/19 13:46:37

1. 赋值运算符重载

1.1 运算符重载

当运算符被⽤于类类型的对象时,C++语⾔允许我们通过运算符重载的形式指定新的含义。C++规定类类型对象使⽤运算符时,必须转换成调⽤对应运算符重载,若没有对应的运算符重载,则会编译报错。
运算符重载是具有特殊名字的函数,他的名字是由operator和后⾯要定义的运算符共同构成。和其他函数⼀样,它也具有其返回类型和参数列表以及函数体。
重载运算符函数的参数个数和该运算符作⽤的运算对象数量⼀样多。⼀元运算符有⼀个参数,⼆元运算符有两个参数,⼆元运算符的左侧运算对象传给第⼀个参数,右侧运算对象传给第⼆个参数。
如果⼀个重载运算符函数是成员函数,则它的第⼀个运算对象默认传给隐式的this指针,因此运算符重载作为成员函数时,参数⽐运算对象少⼀个。
运算符重载以后,其优先级和结合性与对应的内置类型运算符保持⼀致。
不能通过连接语法中没有的符号来创建新的操作符:⽐如operator@。
.* :: sizeof ?: . 注意以上5个运算符不能重载。(选择题⾥⾯常考,⼤家要记⼀下)
重载操作符⾄少有⼀个类类型参数,不能通过运算符重载改变内置类型对象的含义,如: int operator+(int x, int y)
⼀个类需要重载哪些运算符,是看哪些运算符重载后有意义,⽐如Date类重载operator-就有意义,但是重载operator+就没有意义。
重载++运算符时,有前置++和后置++,运算符重载函数名都是operator++,⽆法很好的区分。C++规定,后置++重载时,增加⼀个int形参,跟前置++构成函数重载,⽅便区分。
重载<<和>>时,需要重载为全局函数,因为重载为成员函数,this指针默认抢占了第⼀个形参位置,第⼀个形参位置是左侧运算对象,调⽤时就变成了 对象<<cout,不符合使⽤习惯和可读性。重载为全局函数把ostream/istream放到第⼀个形参位置就可以了,第⼆个形参位置当类类型对象。
#include<iostream>
using namespace std;
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;
}
bool operator==(const Date& d)
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
Date& operator++()
{
cout << "前置++" << endl;
//...
return *this;
}
Date operator++(int)
{
Date tmp;
cout << "后置++" << endl;
//...
return tmp;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2024, 7, 5);
Date d2(2024, 7, 6);
// 运算符重载函数可以显⽰调⽤
d1.operator==(d2);
// 编译器会转换成 d1.operator==(d2);
d1 == d2;
// 编译器会转换成 d1.operator++();
++d1;
// 编译器会转换成 d1.operator++(0);
d1++;
return 0;
}

1.2 赋值运算符重载

赋值运算符重载是⼀个默认成员函数,⽤于完成两个已经存在的对象直接的拷⻉赋值,这⾥要注意跟拷⻉构造区分,拷⻉构造⽤于⼀个对象拷⻉初始化给另⼀个要创建的对象。
赋值运算符重载的特点:
1. 赋值运算符重载是⼀个运算符重载,规定必须重载为成员函数。赋值运算重载的参数建议写成
const 当前类类型引⽤,否则会传值传参会有拷⻉
2. 有返回值,且建议写成当前类类型引⽤,引⽤返回可以提⾼效率,有返回值⽬的是为了⽀持连续赋值场景。
3. 没有显式实现时,编译器会⾃动⽣成⼀个默认赋值运算符重载,默认赋值运算符重载⾏为跟默认拷⻉构造函数类似,对内置类型成员变量会完成值拷⻉/浅拷⻉(⼀个字节⼀个字节的拷⻉),对⾃定义类型成员变量会调⽤他的赋值重载函数

4. 像Date这样的类成员变量全是内置类型且没有指向什么资源,编译器⾃动⽣成的赋值运算符重载就 可以完成需要的拷⻉,所以不需要我们显⽰实现赋值运算符重载。像Stack这样的类,虽然也都是 内置类型,但是_a指向了资源,编译器⾃动⽣成的赋值运算符重载完成的值拷⻉/浅拷⻉不符合我 们的需求所以需要我们⾃⼰实现深拷⻉(对指向的资源也进⾏拷⻉)。像MyQueue这样的类型内部 主要是⾃定义类型Stack成员,编译器⾃动⽣成的赋值运算符重载会调⽤Stack的赋值运算符重载,也不需要我们显⽰实现MyQueue的赋值运算符重载。这⾥还有⼀个⼩技巧,如果⼀个类显⽰实现了析构并释放资源,那么他就需要显⽰写赋值运算符重载,否则就不需要。

1.3 ⽇期类实现

代码如下:

(头文件)

#pragma once
#include<iostream>
using namespace std;
#include<assert.h>
class Date
{
// 友元函数声明
friend ostream& operator<<(ostream& out, const Date& d);
friend istream& operator>>(istream& in, Date& d);
public:
Date(int year = 1900, int month = 1, int day = 1);
void Print() const;
// 直接定义类⾥⾯,他默认是inline
// 频繁调⽤
int GetMonthDay(int year, int month)
{
assert(month > 0 && month < 13);
static int monthDayArray[13] = { -1, 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
// 365天 5h +
if (month == 2 && (year % 4 == 0 && year % 100 != 0) || (year
% 400 == 0))
{
return 29;
}
else
{
return monthDayArray[month];
}
}
bool CheckDate();
bool operator<(const Date& d) const;
bool operator<=(const Date& d) const;
bool operator>(const Date& d) const;
bool operator>=(const Date& d) const;
bool operator==(const Date& d) const;
bool operator!=(const Date& d) const;
// d1 += 天数
Date& operator+=(int day);
Date operator+(int day) const;
// d1 -= 天数
Date& operator-=(int day);
Date operator-(int day) const;
// d1 - d2
int operator-(const Date& d) const;
// ++d1 -> d1.operator++()
Date& operator++();
// d1++ -> d1.operator++(0)
// 为了区分,构成重载,给后置++,强⾏增加了⼀个int形参
// 这⾥不需要写形参名,因为接收值是多少不重要,也不需要⽤
// 这个参数仅仅是为了跟前置++构成重载区分
Date operator++(int);
Date& operator--();
Date operator--(int);
// 流插⼊
// 不建议,因为Date* this占据了⼀个参数位置,使⽤d<<cout不符合习惯
//void operator<<(ostream& out);
private:
int _year;
int _month;
int _day;
};
// 重载
ostream& operator<<(ostream& out, const Date& d);
istream& operator>>(istream& in, Date& d);

// Date.cpp
#include"Date.h"
bool Date::CheckDate()
{
if (_month < 1 || _month > 12
|| _day < 1 || _day > GetMonthDay(_year, _month))
{
return false;
}
else
{
return true;
}
}
Date::Date(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
if (!CheckDate())
{
cout << "⽇期⾮法" << endl;
}
}
void Date::Print() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
// d1 < d2
bool Date::operator<(const Date& d) const
{
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;
}
// d1 <= d2
bool Date::operator<=(const Date& d) const
{
return *this < d || *this == d;
}
bool Date::operator>(const Date& d) const
{
return !(*this <= d);
}
bool Date::operator>=(const Date& d) const
{
return !(*this < d);
}
bool Date::operator==(const Date& d) const
{
return _year == d._year
&& _month == d._month
&& _day == d._day;
}
bool Date::operator!=(const Date& d) const
{
return !(*this == d);
}
// d1 += 50
// d1 += -50
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) const
{
Date tmp = *this;
tmp += day;
return tmp;
}
// d1 -= 100
Date& Date::operator-=(int day)
{
if (day < 0)
{
return *this += -day;
}
_day -= day;
while (_day <= 0)
{
--_month;
if (_month == 0)
{
_month = 12;
_year--;
}
// 借上⼀个⽉的天数
_day += GetMonthDay(_year, _month);
}
return *this;
}
Date Date::operator-(int day) const
{
Date tmp = *this;
tmp -= day;
return tmp;
}
//++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;
}
// d1 - d2
int Date::operator-(const Date& d) const
{
Date max = *this;
Date min = d;
int flag = 1;
if (*this < d)
{
max = d;
min = *this;
flag = -1;
}
int n = 0;
while (min != max)
{
++min;
++n;
}
return n * flag;
}
ostream& operator<<(ostream& out, const Date& d)
{
out << d._year << "年" << d._month << "⽉" << d._day << "⽇" << endl;
return out;
}
istream& operator>>(istream& in, Date& d)
{
cout << "请依次输⼊年⽉⽇:>";
in >> d._year >> d._month >> d._day;
if (!d.CheckDate())
{
cout << "⽇期⾮法" << endl;
}
return in;
}
Test.cpp

#include"Date.h"
void TestDate1()
{
// 这⾥需要测试⼀下⼤的数据+和-
Date d1(2024, 4, 14);
Date d2 = d1 + 30000;
d1.Print();
d2.Print();
Date d3(2024, 4, 14);
Date d4 = d3 - 5000;
d3.Print();
d4.Print();
Date d5(2024, 4, 14);
d5 += -5000;
d5.Print();
}
void TestDate2()
{
Date d1(2024, 4, 14);
Date d2 = ++d1;
d1.Print();
d2.Print();
Date d3 = d1++;
d1.Print();
d3.Print();
/*d1.operator++(1);
d1.operator++(100);
d1.operator++(0);
d1.Print();*/
}
void TestDate3()
{
Date d1(2024, 4, 14);
Date d2(2034, 4, 14);
int n = d1 - d2;
cout << n << endl;
n = d2 - d1;
}
void TestDate4()
{
Date d1(2024, 4, 14);
Date d2 = d1 + 30000;
// operator<<(cout, d1)
cout << d1;
cout << d2;
cin >> d1 >> d2;
cout << d1 << d2;
}
void TestDate5()
{
const Date d1(2024, 4, 14);
d1.Print();
//d1 += 100;
d1 + 100;
Date d2(2024, 4, 25);
d2.Print();
d2 += 100;
d1 < d2;
d2 < d1;
}
int main()
{
return 0;
}

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

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

相关文章

Leetcode—1143. 最长公共子序列【中等】

2024每日刷题&#xff08;155&#xff09; Leetcode—1143. 最长公共子序列 实现代码 class Solution { public:int longestCommonSubsequence(string text1, string text2) {int m text1.length();int n text2.length();vector<vector<int>> dp(m 1, vector&…

sadtalker推理的时候报错:IndexError: Cannot choose from an empty sequence

问题描述 在进行推理的时候&#xff0c;报错IndexError: Cannot choose from an empty sequence&#xff0c;如下图 解决办法&#xff1a; 这个报错是因为你输入的音频太短了&#xff0c;不到1秒就会报这个错。你可以输入个大于1秒的视频试一下。 也可以修改代码解决这个问题…

Python教程(十四):Requests模块详解

目录 专栏列表前言&#xff1a;安装 Requests查看包安装情况&#xff1a; RESTful 介绍RESTful API设计原则示例 基本用法1. 查询ID为1的用户&#xff08;GET&#xff09;2. 创建新用户&#xff08;POST&#xff09;3. 更新ID 为 1 的用户&#xff08;PUT&#xff09;4. 删除ID…

Haproxy讲解

Haproxy: haproxy是一个开源的高性能反向代理和负载均衡器&#xff0c;主要用于‌TCP和‌HTTP流量管理。 功能和特点&#xff1a;haproxy能够处理大量的并发连接&#xff0c;支持TCP和HTTP协议&#xff0c;具有高可用性和负载均衡功能。它特别适用于需要处理大量流量的网站&am…

AI终于会画手了,Flux.1一出世就直接碾压Stable Diffusion(SD)和Midjourney(MJ)

Flux.1模型一发布&#xff0c;AI文生图终于会画手了&#xff0c;Flux.1模型比Stable Diffusion&#xff08;SD&#xff09;和Midjourney&#xff08;MJ&#xff09;更能将手部和长文本生成得更好更合理。 Flux.1模型生成的图&#xff0c;现在手部不再有畸形了。 同时&#xff…

hfs通过stunnel实现https访问

hfs通过stunnel实现https访问 REF:官方文档&#xff0c;有点老旧 https://blog.51cto.com/u_15015155/2554641 步骤 下载stunnel工具 download (笔者用的是windows的) 下载stunnel途中会进行本地证书的制作&#xff08;也可以用openssl自定义证书&#xff09;&#xff0c;如…

C++ 适配器

适配器 适配器是一种设计模式&#xff0c;我们最终实现的功能可以通过不同的路径来实现&#xff0c;那么这个路径就可以称作适配器。 例如下面的例子&#xff1a; 那么在c中也有适配器&#xff0c;例如stack、queue、priority_queue&#xff0c;它们并不是使用了什么新的内存…

【python爬虫】利用Python爬取天气数据,并做可视化分析

首先登录网站&#xff0c;查看网页内容及数据格式(使用代码查看内容)&#xff0c;选择两个城市及对应月份&#xff0c;爬取对应天气数据&#xff0c;进行数据预处理(如缺失值处理、数据类型转换、字符串截取等)&#xff0c;数据的初步探索性分析(如描述性统计、数据可视化查看数…

应对猫咪掉毛挑战,希喂、小米热门宠物空气净化器实测功效PK

随着养宠人群的增多&#xff0c;铲屎官们的需求日益增长&#xff0c;市场上出现了很多品牌的宠物空气净化器。然而&#xff0c;产品质量参差不齐&#xff0c;给消费者选择带来不少困难。劣质宠物空气净化器不仅无法有效去除宠物毛发、皮屑、异味及空气中的有害微粒&#xff0c;…

启动虚拟机:另一个程序已锁定文件的一部分,进程无法访问,打不开磁盘xxx或它所依赖的某个快照磁盘

theme: nico 你们好&#xff0c;我是金金金。 场景 启动虚拟机时报错如下 造成error的原因 这是一种虚拟机的保护机制 虚拟机在运行时&#xff0c;为了防止数据被篡改&#xff0c;会将所运行的文件保护起来。 当虚拟机突然崩溃或强制结束导致异常退出&#xff08;我昨天是直接…

【C++】设计模式 — 从零开始认识单例模式

人的一生本来就是一场有来无回的冒险。 --- priest 《残次品》--- 设计模式 — 单例模式 1 设计模式2 单例模式2.1 饿汉模式2.2 懒汉模式 3 总结 1 设计模式 设计模式&#xff08;Design Pattern&#xff09;是一套被反复使用、多数人知晓的、经过分类的、代码设计经验的总结…

YZ系列工具之YZ05:代码运行中调用“计算器”使用说明

我给VBA下的定义&#xff1a;VBA是个人小型自动化处理的有效工具。利用好了&#xff0c;可以大大提高自己的工作效率&#xff0c;而且可以提高数据的准确度。我的教程一共九套一部VBA手册&#xff0c;教程分为初级、中级、高级三大部分。是对VBA的系统讲解&#xff0c;从简单的…

语音播报加入预警系统

语音播报加入预警系统 引言 引入语音警报 我们前一章, 已经把jq8900-16p模块, 单独进行了测试, 可以通过发送命令, 让模块播报设定好的声音。那么语音播报&#xff0c; 在预警系统中&#xff0c; 也必不可少&#xff0c; 我们现在有了led灯光警报,如果主人在睡觉, 是不能及时…

redis列表若干记录

2、列表 ziplist ziplist参数 entry结构 entry-data:节点存储的元素prelen&#xff1a;记录前驱节点长度encoding&#xff1a;当前节点编码格式encoding encoding属性 使用多个子节点存储节点元素长度&#xff0c;这种多字节数据存储在计算机内存中或者进行网络传输的时的字节…

排序算法——插入排序

一、插入排序概念 直接插入排序&#xff08;Insertion Sort&#xff09;是一种简单的排序算法&#xff0c;它的工作原理类似于人们手动排序卡片的方式。该算法通过构建有序序列&#xff0c;对于未排序数据&#xff0c;在已排序序列中从后向前扫描&#xff0c;找到相应位置并插…

ubuntu、cpolar、api开启映射之路

1.国内cpolar安装 curl -L https://www.cpolar.com/static/downloads/install-release-cpolar.sh | sudo bash或 cpolar短链接安装方式&#xff1a;(国外使用&#xff09; curl -sL https://git.io/cpolar | sudo bash2.查看版本号&#xff0c;正常显示即为安装成功 cpolar …

HR系统怎么选?2024年10大热门工具评测

本文中介绍的工具有&#xff1a;Moka、名才MCHR、HiHR、华天动力HRM、红海eHR、易路eRoad、宏景HJSOFT、Gusto、Zenefits、BambooHR。 在当今竞争激烈的商业环境中&#xff0c;找到一个适合企业的HR系统可能是一个令人头疼的问题。市面上的HR工具琳琅满目&#xff0c;各有千秋&…

Django 自定义用户 VS 用户资料

Django是一个流行的Web框架&#xff0c;它提供了一套完整的用户认证系统&#xff0c;其中包括内置的User模型用于存储基本的用户信息&#xff0c;如用户名、密码等。然而&#xff0c;如果我们需要更详细的用户资料管理&#xff0c;比如添加更多的字段或者自定义验证规则&#x…

Linux 常见的冷知识集锦

一、前言 本文旨在记录那些常见的Linux概念和名词&#xff0c;但这些又没经常直接使用到&#xff0c;更多在底层运行&#xff0c;见过却又不是特别清楚的碎片知识&#xff0c;以温故知新。 二、知识点和概念说明 2.1、POSIX标准/协议 POSIX&#xff08;Portable Operating S…

股票技术指标 RSI KDJ MACD

具体指标解释&#xff0c;大模型都有&#xff0c;只说作用 RSI&#xff08;Relative Strength Index&#xff0c;相对强弱指数&#xff09; 超买和超卖水平&#xff1a;通常情况下&#xff0c;RSI值超过70表示市场可能超买&#xff0c;而低于30表示可能超卖。这并不意味着价格…