当前位置: 首页 > 编程日记 > 正文

c++运算符重载总结

c++的一大特性就是重载(overload),通过重载可以把功能相似的几个函数合为一个,使得程序更加简洁、高效。在c++中不止函数可以重载,运算符也可以重载。由于一般数据类型间的运算符没有重载的必要,所以运算符重载主要是面向对象之间的。

1.一般运算符重载

在进行对象之间的运算时,程序会调用与运算符相对应的函数进行处理,所以运算符重载有两种方式:成员函数和友元函数。成员函数的形式比较简单,就是在类里面定义了一个与操作符相关的函数。友元函数因为没有this指针,所以形参会多一个。

  1. class A
  2. {
  3. public:
  4. A(int d):data(d){}
  5. A operator+(A&);//成员函数
  6. A operator-(A&);
  7. A operator*(A&);
  8. A operator/(A&);
  9. A operator%(A&);
  10. friend A operator+(A&,A&);//友元函数
  11. friend A operator-(A&,A&);
  12. friend A operator*(A&,A&);
  13. friend A operator/(A&,A&);
  14. friend A operator%(A&,A&);
  15. private:
  16. int data;
  17. };
  18. //成员函数的形式
  19. A A::operator+(A &a)
  20. {
  21. return A(data+a.data);
  22. }
  23. A A::operator-(A &a)
  24. {
  25. return A(data-a.data);
  26. }
  27. A A::operator*(A &a)
  28. {
  29. return A(data*a.data);
  30. }
  31. A A::operator/(A &a)
  32. {
  33. return A(data/a.data);
  34. }
  35. A A::operator%(A &a)
  36. {
  37. return A(data%a.data);
  38. }
  39. //友元函数的形式
  40. A operator+(A &a1,A &a2)
  41. {
  42. return A(a1.data+a2.data);
  43. }
  44. A operator-(A &a1,A &a2)
  45. {
  46. return A(a1.data-a2.data);
  47. }
  48. A operator*(A &a1,A &a2)
  49. {
  50. return A(a1.data*a2.data);
  51. }
  52. A operator/(A &a1,A &a2)
  53. {
  54. return A(a1.data/a2.data);
  55. }
  56. A operator%(A &a1,A &a2)
  57. {
  58. return A(a1.data%a2.data);
  59. }
  60. //然后我们就可以对类的对象进行+、-、*、/了。
  61. void main(void)
  62. {
  63. A a1(1),a2(2),a3(3);
  64. a1=a2+a3;
  65. //或者
  66. a1=a2.operator+(a3);
  67. }

注意:在进行a2+a3的时候会出错,因为我们在上面对+定义了两种方法,去掉一种即可。

2.关系运算符重载

因为函数体比较简单,后面我就只给出成员函数形式的函数声明了,关系运算符有==,!=,<,>,<=,>=。

  1. bool operator == (const A& );
  2. bool operator != (const A& );
  3. bool operator < (const A& );
  4. bool operator <= (const A& );
  5. bool operator > (const A& );
  6. bool operator >= (const A& );

3.逻辑运算符重载

  1. bool operator || (const A& );
  2. bool operator && (const A& );
  3. bool operator ! ();

4.单目运算符重载

这里的+、-是正负的意思,放在对象前面。

  1. A& operator + ();
  2. A& operator - ();
  3. A* operator & ();
  4. A& operator * ();

5.自增减运算符重载

++和–根据位置的不同有四种情况,都可以重载。

  1. A& operator ++ ();//前置++
  2. A operator ++ (int);//后置++
  3. A& operator --();//前置--
  4. A operator -- (int);//后置--

6.位运算符重载

按位操作。

  1. A operator | (const A& );
  2. A operator & (const A& );
  3. A operator ^ (const A& );
  4. A operator << (int i);
  5. A operator >> (int i);
  6. A operator ~ ();

7.赋值运算符重载

没有=哦。

  1. A& operator += (const A& );
  2. A& operator -= (const A& );
  3. A& operator *= (const A& );
  4. A& operator /= (const A& );
  5. A& operator %= (const A& );
  6. A& operator &= (const A& );
  7. A& operator |= (const A& );
  8. A& operator ^= (const A& );
  9. A& operator <<= (int i);
  10. A& operator >>= (int i);

8.内存运算符重载

  1. void *operator new(size_t size);
  2. void *operator new(size_t size, int i);
  3. void *operator new[](size_t size);
  4. void operator delete(void*p);
  5. void operator delete(void*p, int i, int j);
  6. void operator delete [](void* p);

9.特殊运算符重载

上面的运算符重载都有两种方式,而下面的运算符只能用一种,特殊吧。 这些运算符的重载只能是成员函数。

  1. A& operator = (const A& );
  2. char operator [] (int i);//返回值不能作为左值
  3. const char* operator () ();
  4. T operator -> ();
  5. //类型转换符
  6. operator char* () const;
  7. operator int ();
  8. operator const char () const;
  9. operator short int () const;
  10. operator long long () const;
  11. //还有很多就不写了

而这些只能以友元函数的形式重载

  1. friend inline ostream &operator << (ostream&, A&);//输出流
  2. friend inline istream &operator >> (istream&, A&);//输入流

10.总结

两种重载方式的比较:

  • 一般情况下,单目运算符最好重载为类的成员函数;双目运算符则最好重载为类的友元函数。
  • 以下一些双目运算符不能重载为类的友元函数:=、()、[]、->。
  • 类型转换函数只能定义为一个类的成员函数而不能定义为类的友元函数。 C++提供4个类型转换函数:reinterpret_cast(在编译期间实现转换)、const_cast(在编译期间实现转换)、stactic_cast(在编译期间实现转换)、dynamic_cast(在运行期间实现转换,并可以返回转换成功与否的标志)。
  • 若一个运算符的操作需要修改对象的状态,选择重载为成员函数较好。
  • 若运算符所需的操作数(尤其是第一个操作数)希望有隐式类型转换,则只能选用友元函数。
  • 当运算符函数是一个成员函数时,最左边的操作数(或者只有最左边的操作数)必须是运算符类的一个类对象(或者是对该类对象的引用)。如果左边的操作数必须是一个不同类的对象,或者是一个内部 类型的对象,该运算符函数必须作为一个友元函数来实现。
  • 当需要重载运算符具有可交换性时,选择重载为友元函数。

注意事项:

  1. 除了类属关系运算符”.“、成员指针运算符”.*“、作用域运算符”::“、sizeof运算符和三目运算符”?:“以外,C++中的所有运算符都可以重载。
  2. 重载运算符限制在C++语言中已有的运算符范围内的允许重载的运算符之中,不能创建新的运算符。
  3. 运算符重载实质上是函数重载,因此编译程序对运算符重载的选择,遵循函数重载的选择原则。
  4. 重载之后的运算符不能改变运算符的优先级和结合性,也不能改变运算符操作数的个数及语法结构。
  5. 运算符重载不能改变该运算符用于内部类型对象的含义。它只能和用户自定义类型的对象一起使用,或者用于用户自定义类型的对象和内部类型的对象混合使用时。
  6. 运算符重载是针对新类型数据的实际需要对原有运算符进行的适当的改造,重载的功能应当与原有功能相类似,避免没有目的地使用重载运算符。

转载于:https://www.cnblogs.com/carekee/articles/5240983.html

相关文章:

一道面试题:js返回函数, 函数名后带多个括号的用法及join()的注意事项

博客搬迁&#xff0c;给你带来的不便&#xff0c;敬请谅解&#xff01; http://www.suanliutudousi.com/2017/11/13/js%E8%BF%94%E5%9B%9E%E5%87%BD%E6%95%B0%E4%B8%AD%EF%BC%8C%E5%87%BD%E6%95%B0%E5%90%8D%E5%90%8E%E5%B8%A6%E5%A4%9A%E4%B8%AA%E6%8B%AC%E5%8F%B7%E7%9A%84%E…

小程序画布画海报保存成图片可以保存实现完整代码

老规矩先来个效果图&#xff1a; 因为是截图所以会有些模糊&#xff0c;在真机上会比较清晰 下面针对效果图来看看里面都画了什么元素&#xff0c;代码在文章的最后&#xff0c;大家想直接拷代码可以略过这&#xff0c;这里是方便大家理解代码。 首先&#xff0c;咱们的海报有…

fcm和firebase_我如何最终使Netlify Functions,Firebase和GraphQL一起工作

fcm和firebaseIn a previous post I confessed defeat in attempting to get an AWS Lambda GraphQL server to connect to a Firebase server. I didn’t give up right away, though, and a short time later found a different Node package to achieve what I couldn’t be…

深入了解Mvc路由系统

请求一个MVC页面的处理过程 1.浏览器发送一个Home/Index 的链接请求到iis。iis发现时一个asp.net处理程序。则调用asp.net_isapi 扩展程序发送asp.net框架 2.在asp.net的第七个管道事件中会遍历UrlRoutingModule中RouteCollection的RoteBase集合 通过调用其GetRouteData方法进行…

uni-app h5页面左上角出现“取消“字眼解决办法

在项目根目录的index.html中加上一行代码 <link rel"stylesheet" href"<% BASE_URL %>static/index.<% VUE_APP_INDEX_CSS_HASH %>.css" /> 如图&#xff1a;

unity编辑器扩展_01(在工具栏中创建一个按钮)

代码&#xff1a; [MenuItem("Tools/Test",false,1)] static void Test() { Debug.Log("test"); } 注意&#xff1a;MenuItem中第一个参数:需要创建选项在工具栏中的路径&#xff0c;此路径的父目录可以是Unity中已存在的&#xff0c;也…

postgres语法_SQL Create Table解释了MySQL和Postgres的语法示例

postgres语法A table is a group of data stored in a database.表是存储在数据库中的一组数据。 To create a table in a database you use the CREATE TABLE statement. You give a name to the table and a list of columns with its datatypes.要在数据库中创建表&#…

jquery-ajax请求:超时设置,增加 loading 提升体验

前端发送Ajax请求到服务器&#xff0c;服务器返回数据这一过程&#xff0c;因原因不同耗时长短也有差别&#xff0c;且这段时间内页面显示空白。如何优化这段时间内的交互体验&#xff0c;以及长时间内服务器仍未返回数据这一问题&#xff0c;是我们开发中不容忽视的重点。 常见…

第三章.SQL编程

2016年3月2日13:55:17(记忆笔记) 变量是存储数据的容器。 如何在SQL中定义自己的变量&#xff01; First:第一套变量定义 整型 Declare num int Set num10 Print num 第二套变量定义 字符串类型(char varchar nvarchar) Declare name nvarchar(32) Set name’小帅’ Pri…

移动端自动播放音视频实现代码

视频组件 <video :custom-cache"false" :src"item.voideoUrl" :id"audio index" :vslide-gesture-in-fullscreen"false" :direction0 :enable-progress-gesture"false" :show-fullscreen-btn"false" loop obj…

grafana美人鱼_编码美人鱼–我如何从海洋生物学家转到前端开发人员

grafana美人鱼I have wanted to share my story for a while, but I didn’t know exactly how to start, or even what name to give it. 我想分享我的故事一段时间&#xff0c;但我不知道确切的开头&#xff0c;甚至不知道用什么名字。 But recently I was talking with som…

网络安全基础扫盲

1. 名词解释 APT 高级持续性威胁。利用先进的攻击手段对特定目标进行长期持续性网络攻击的攻击形式。其高级性主要体现在APT在发动攻击之前需要对攻击对象的业务流程和目标系统进行精确的收集。 VPN 虚拟专用网络&#xff08;Virtual private network&#xff09; VPN是Virtual…

Install Package and Software

svn http://tortoisesvn.sourceforge.net/ git https://download.tortoisegit.org/ http://git-for-windows.github.io/转载于:https://www.cnblogs.com/exmyth/p/5246529.html

小程序保存网络图片

小程序保存网络实现流程&#xff1a; 1.把图片下载到本地 2.检查用户的授权状态&#xff08;三种状态&#xff1a;未授权&#xff0c;已授权&#xff0c;未同意授权&#xff09;&#xff0c;判断是否授权保存图片的能力&#xff0c;如果是用户点击了不同意授权给小程序保存图…

aws 认证_引入#AWSCertified挑战:您的第一个AWS认证之路

aws 认证You may already know that Amazon Web Services (AWS) is the largest, oldest, and most popular cloud service provider. But did you know they offer professional certifications, too?您可能已经知道Amazon Web Services(AWS)是最大&#xff0c;最古老和最受欢…

node!!!

node.js Node是搞后端的&#xff0c;不应该被被归为前端&#xff0c;更不应该用前端的观点去理解&#xff0c;去面试node开发人员。所以这份面试题大全&#xff0c;更侧重后端应用与对Node核心的理解。 github地址: https://github.com/jimuyouyou/node-interview-questions 注…

POJ 1556 The Doors(计算几何+最短路)

这题就是&#xff0c;处理出没两个点。假设能够到达&#xff0c;就连一条边&#xff0c;推断可不能够到达&#xff0c;利用线段相交去推断就可以。最后求个最短路就可以 代码&#xff1a; #include <cstdio> #include <cstring> #include <algorithm> #inclu…

* core-js/modules/es6.array.fill in ./node_modules/_cache-loader@2.0.1@cache-loader/dist/cjs.js??ref

运行Vue项目报错&#xff0c;报错截图如下&#xff1a; 导致该错误的原因是core-js版本不对&#xff1a; 解决方法&#xff1a;安装淘宝镜像 $ cnpm install core-js2 安装完成重新运行就可以了 外&#xff1a; 清除npm缓存命令 &#xff1a; npm cache clean -f

github创建静态页面_如何在10分钟内使用GitHub Pages创建免费的静态站点

github创建静态页面Static sites have become all the rage, and with good reason – they are blazingly fast and, with an ever growing number of supported hosting services, pretty easy to set up. 静态站点已成为流行&#xff0c;并且有充分的理由-它们非常快速&…

小程序生成网址链接,网址链接跳转小程序

登录小程序后台&#xff0c;点击右上角的工具&#xff0c;生成小程序URL Scheme &#xff0c; 可以得出一个 weixin://dl/business/?tbAXXXXX 这样的链接&#xff0c;点击就可以调整到小程序拉&#xff0c;但是这种只能在微信打开哦。

appium-chromedriver@3.0.1 npm ERR! code ELIFECYCLE npm ERR! errno 1

解决方法&#xff1a; npm install appium-chromedriver3.0.1 --ignore-scripts 或者&#xff08;安装方法&#xff09;&#xff1a; npm install appium-chromedriver --chromedriver_cdnurlhttp://npm.taobao.org/mirrors/chromedriver 官网地址&#xff1a;https://www.npmj…

linux下QT Creator常见错误及解决办法

最近因为在做一个关于linux下计算机取证的小项目&#xff0c;需要写一个图形界面&#xff0c;所以想到了用QT来写&#xff0c;选用了linux下的集成开发环境QT Creator5.5.1&#xff0c;但刚刚安装好&#xff0c;竟然连一个"hello world"的样例都跑不起来&#xff0c;…

如何使用JavaScript Math.floor生成范围内的随机整数-已解决

快速解决方案 (Quick Solution) function randomRange(myMin, myMax) {return Math.floor(Math.random() * (myMax - myMin 1) myMin); }代码说明 (Code Explanation) Math.random() generates our random number between 0 and ≈ 0.9. Math.random()生成介于0和≈0.9之间的…

小白的未来与展望

新的起点&#xff0c;新的挑战与机遇 1.在php制作&#xff0c;研发上的知识点及语法编辑重点要按照老师的要求完全掌握。作为对自己以后前进方向上坚实的基础。 2.php语言开发编写上&#xff0c;希望能够在不久的将来能够有自己的独特的理解及研发出更多的更为简洁方便的编写方…

uniapp移动端H5在线预览PDF等文件实现源码及注解

uniapp移动端H5预览文件实现分为两个场景处理: (这里以预览PDF文件为示例,在线预览就是查看网络文件) 1. IOS客户端预览PDF文件 IOS客户端预览PDF文件可以通过跳转文件地址实现预览,因为苹果手机的浏览器自带阅读器 2. 安卓客户端预览PDF文件 安卓客户端需要在源码添…

如何使用Python和Tkinter构建Toy Markdown编辑器

Markdown editors are trending these days. Everybody is creating a markdown editor, and some of them are innovative while some of them are boring. Markdown编辑器近来呈趋势。 每个人都在创建降价编辑器&#xff0c;其中有些人很创新&#xff0c;而有些人很无聊。 A…

Hadoop 分布式环境搭建

1.集群机器&#xff1a; 1台 装了 ubuntu 14.04的 台式机 1台 装了ubuntu 16.04 的 笔记本 &#xff08;机器更多时同样适用&#xff09; 搭建步骤&#xff1a; 准备工作&#xff1a; 使两台机器处于同一个局域网&#xff1a;相互能够 ping 通 主机名称 …

常见报错——Uncaught TypeError: document.getElementsByClassName(...).addEventListener is not a function...

这是因为选择器没有正确选择元素对象 document.getElementsByClassName(...)捕捉到的是该类名元素的数组 正确的访问方式应该是&#xff1a; document.getElementsByClassName(...)[0].addEventListener... 使用遍历为每个class添加监听&#xff1a; var classObj document.ge…

uniapp富文本兼容视频实现方案

使用 mp-html 富文本插件&#xff0c;就可以支持富文本内的视频播放。 安装&#xff1a; npm install mp-html 使用方法 <template><view><mp-html :content"html" /></view> </template> <script>import mpHtml from /comp…

循环神经网络 递归神经网络_如何用递归神经网络预测空气污染

循环神经网络 递归神经网络After the citizen science project of Curieuze Neuzen, I wanted to learn more about air pollution to see if I could make a data science project out of it. On the website of the European Environment Agency, you can find a huge amount…