当前位置: 首页 > news >正文

C++——类和对象(3)

目录

一、赋值运算符重载

1.定义和使用

2.特点

二、日期类的实现

(1)Date.h

(2)Date.cpp

三、取地址运算符重载

1.const成员函数

2.取地址运算符重载

四、写在最后 


一、赋值运算符重载

1.定义和使用

(1)当运算符被用于类型的对象时,C++允许我们通过运算符重载的形式指定新的含义。C++规定:类类型对象使用运算符时,必须转换去调用对应运算符重载,若没有对应的运算符重载,则会编译报错。

(2)运算符重载是具有特殊名字的函数,它的名字是由operator和后面要定义的运算符共同构成。和其他函数⼀样,它也具有其返回类型参数列表以及函数体

(3)重载运算符函数的参数个数和该运算符作用的运算对象数量⼀样多。比如:⼀元运算符有⼀个参数,二元运算符有两个参数,二元运算符的左侧运算对象传给第⼀个参数,右侧运算对象传给第⼆个参数。

(4)如果⼀个重载运算符函数是成员函数,则它的第⼀个运算对象默认传给隐式的this指针,因此运算符重载作为成员函数时,参数比运算对象少⼀个。

(5)运算符重载以后,其优先级和结合性与对应的内置类型运算符保持⼀致。

(6)不能通过连接语法中没有的符号来创建新的操作符:比如:operator@。

(7).*   ::    sizeof     ?:     .   注意以上5个运算符不能重载。

#include<iostream>
using namespace std;class A
{
public:void func(){cout << "A::func()" << endl;}
};typedef void(A::*PF)(); //成员函数指针类型int main()
{// C++规定成员函数要加&才能取到函数指针 PF pf = &A::func;A obj;//定义ob类对象temp // 对象调⽤成员函数指针时,使⽤.*运算符 (obj.*pf)();return 0;
}

(8)重载操作符至少有⼀个类类型参数,不能通过运算符重载改变内置类型对象的含义。

//编译报错:"operator + "必须有至少一个类类型的形参
int operator(int x, int y)
{return x - y;
}

(9)⼀个类需要重载哪些运算符,是看哪些运算符重载后有意义。比如Date类重载operator-就有意义,但是重载operator*就没有意义。

(10)重载++运算符时,有前置++和后置++,但运算符重载函数名都是operator++,无法很好的区分。 C++规定:后置++重载时,增加⼀个int形参,跟前置++构成函数重载,方便区分。

#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;
}

(11) 重载>> 和 << 时,需要重载为全局函数,因为如果重载为成员函数,this指针默认抢占了第⼀个形参位置,第⼀个形参位置是左侧运算对象,调用时就变成了对象 << cout,不符合使用的习惯,降低了可读性。

重载为全局函数把ostream / istream放到第⼀个形参位置就可以了,第⼆个形参位置当类类型对 象。

2.特点

(1)赋值运算符重载是⼀个默认成员函数,用于完成两个已经存在的对象直接的拷贝赋值,这里要注意和拷贝构造区分,拷贝构造用于⼀个对象拷贝初始化给另⼀个要创建的对象。

int main()
{Date d1(2024, 7, 5);Date d2(d1);Date d3(2024, 7, 6);d1 = d3;// 需要注意这⾥是拷⻉构造,不是赋值重载 // 赋值重载完成两个已经存在的对象直接的拷⻉赋值// ⽽拷⻉构造⽤于⼀个对象拷⻉初始化给另⼀个要创建的对象 Date d4 = d1;return 0;
}

(2)赋值运算符重载是⼀个运算符重载,规定必须重载为成员函数。赋值运算重载的参数建议写成 const 当前类类型引用,否则会传值传参会有拷贝。

(3)有返回值,且建议写成当前类类型引用,引用返回可以提高效率,有返回值的目的是为了支持连续赋值场景。

// 传引⽤返回,减少拷⻉ 
// d1 = d2;Date& operator=(const Date& d)
{// 检查⾃⼰给⾃⼰赋值的情况 if (this != &d){_year = d._year;_month = d._month;_day = d._day;}// d1 = d2表达式的返回对象应该为d1,也就是*this return *this;
}

(4)没有显式实现时,编译器会自动生成⼀个默认赋值运算符重载,默认赋值运算符重载的行为跟默认拷贝构造函数类似,对内置类型成员变量会完成值拷贝 / 浅拷贝(⼀个字节⼀个字节的拷贝),对自定义类型成员变量会调用它的赋值重载函数。

(5)像Date这样的类成员变量全是内置类型没有指向什么资源,编译器自动生成的赋值运算符重载就可以完成需要的拷贝,所以不需要我们显示实现赋值运算符重载。

像Stack这样的类,虽然也都是内置类型,但是_a数组指向了资源,编译器自动生成的赋值运算符重载完成的值拷贝 / 浅拷贝不符合我们的需求,所以需要我们自己实现深拷贝(对指向的资源也进行拷贝)。

像MyQueue这样的类型内部主要是自定义类型Stack成员,编译器自动生成的赋值运算符重载会调用Stack的赋值运算符重载, 也不需要我们显示实现MyQueue的赋值运算符重载。

(6)还有⼀个小技巧,如果⼀个类显示实现了析构并释放资源,那么它就需要显示写赋值运算符重载,否则就不需要。

二、日期类的实现

(1)Date.h

#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 }; 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 - d2int 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);

(2)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;
}

三、取地址运算符重载

1.const成员函数

 (1)将const修饰的成员函数称之为const成员函数,const修饰成员函数放到成员函数参数列表的后面。

(2)const实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。 const 修饰Date类的Print成员函数,Print隐含的this指针由 Date* const this 变为 const Date* const this。

#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(const Date* const this) constvoid Print() const{cout << _year << "-" << _month << "-" << _day << endl;}private:int _year;int _month;int _day;
};int main()
{// 这⾥⾮const对象也可以调⽤const成员函数是⼀种权限的缩⼩ Date d1(2024, 7, 5);d1.Print();const Date d2(2024, 8, 5);d2.Print();return 0;
}

2.取地址运算符重载

 取地址运算符重载分为普通取地址运算符重载和const取地址运算符重载,⼀般这两个函数编译器自动生成的就可以够我们用了,不需要去显示实现。

除非⼀些很特殊的场景,比如我们不想让别人取到当前类对象的地址,就可以自己实现⼀份,胡乱返回⼀个地址。

class Date
{ 
public :Date* operator&(){return this;// return nullptr;}const Date* operator&()const{return this;// return nullptr;}private :int _year ; // 年 int _month ; // ⽉ int _day ; // ⽇ 
};

四、写在最后 

下期我们将学习《类和对象(下)》!

敬请期待~

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • ppt文件怎么压缩变小一些?8种压缩PPT文件的方法推荐
  • 网络安全应急响应概述
  • 配置Red Hat Enterprise Linux 7 YUM源
  • 免费音乐剪辑软件大揭秘:2024 大学生的音乐创作利器
  • CTFshow--爆破靶场全攻略
  • Python 课程14-TensorFlow
  • 张养浩,文坛政坛的双重巨匠
  • string类(C++)
  • 轴对齐包围盒(AABB)和有向包围盒(OBB)介绍
  • oracle停止当前运行的JOB或kill会话
  • synchronized和ReentrantLock区别?
  • 图论篇--代码随想录算法训练营第六十一天打卡| Floyd 算法,A*算法
  • css实现居中的方法
  • 悲观锁与乐观锁
  • 一个WebSocket的前端封装类
  • 【Leetcode】104. 二叉树的最大深度
  • Django 博客开发教程 16 - 统计文章阅读量
  • el-input获取焦点 input输入框为空时高亮 el-input值非法时
  • flask接收请求并推入栈
  • HTTP那些事
  • HTTP中的ETag在移动客户端的应用
  • leetcode讲解--894. All Possible Full Binary Trees
  • 个人博客开发系列:评论功能之GitHub账号OAuth授权
  • 基于组件的设计工作流与界面抽象
  • 将 Measurements 和 Units 应用到物理学
  • 蓝海存储开关机注意事项总结
  • 前端面试题总结
  • 双管齐下,VMware的容器新战略
  • 小程序开发中的那些坑
  • 学习ES6 变量的解构赋值
  • 做一名精致的JavaScripter 01:JavaScript简介
  • TPG领衔财团投资轻奢珠宝品牌APM Monaco
  • ​LeetCode解法汇总2670. 找出不同元素数目差数组
  • ​渐进式Web应用PWA的未来
  • ​经​纬​恒​润​二​面​​三​七​互​娱​一​面​​元​象​二​面​
  • #define、const、typedef的差别
  • $().each和$.each的区别
  • (C#)Windows Shell 外壳编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令...
  • (STM32笔记)九、RCC时钟树与时钟 第二部分
  • (附源码)计算机毕业设计SSM智慧停车系统
  • (面试必看!)锁策略
  • (十)T检验-第一部分
  • (十一)手动添加用户和文件的特殊权限
  • (四)linux文件内容查看
  • (一)【Jmeter】JDK及Jmeter的安装部署及简单配置
  • (转)Sql Server 保留几位小数的两种做法
  • * 论文笔记 【Wide Deep Learning for Recommender Systems】
  • .Net Framework 4.x 程序到底运行在哪个 CLR 版本之上
  • [ C++ ] STL---string类的使用指南
  • [ 云计算 | Azure 实践 ] 在 Azure 门户中创建 VM 虚拟机并进行验证
  • []T 还是 []*T, 这是一个问题
  • [AI aider] 打造终端AI搭档:Aider让编程更智能更有趣!
  • [Android] Amazon 的 android 音视频开发文档
  • [Ariticle] 厚黑之道 一 小狐狸听故事
  • [C++]spdlog学习