浅析C++中的重载运算符(重点是重载+=)
来源:互联网 发布:飞鱼网络电视看不了 编辑:程序博客网 时间:2024/04/28 01:43
C++中的重载运算符很多人再熟悉不过了,你可能会轻松的写出重载+,-,*,/。但是当你第一次写重载+=时,也许会有些迷茫。
先来点家常的,写一个赋值运算符:
Contact& operator=( const Contact& rhs ) { if(this == &rhs) return *this char* tempName = new char[strlen( rhs.name ) + 1]; delete[] name; name = tempName; strcpy( name, rhs.name ); age = rhs.age; return *this;}
第一个问题,为何返回对象的引用:
答曰:可以实现对象的连等。
再来段家常的:
Time operator+(const Time & t)const{ Time sum; sum.minutes = minutes + t.minutes ; sum.hours = hours + t.hours + sum.minutes / 60; sum.minutes %= 60; return sum;}Time operator-(const Time & t)const{ Time diff; int tot1, tot2; tot1 = t.minutes +60 * t.hours; tot2 = minutes + 60 * hours; diff.minutes = (tot2 - tot1) % 60; diff.hours = (tot2 - tot1) / 60; return diff;}
我们可以看到上面重载了+,-,但是为什么没有返回引用了:
答曰:返回了被调用函数中的局部变量,所以不能按引用的方式返回!
关键的部分来了,如果你第一次接触重载+=,我想可以对你有一点点帮助吧!因为你可能迷茫如何扩大空间!
还是看看代码吧:
const String &String::operator+=(const String &right ) { char *tempPtr=sPtr; // hold to be able to delete length +=right.length; // new String length sPtr= newchar[ length + 1 ]; // create space assert(sPtr!= 0);//terminate if memory not allocated strcpy(sPtr,tempPtr); // left part of new String strcat(sPtr,right.sPtr);// right part of new String delete [ ]tempPtr; // reclaim old space return*this; // enables cascaded calls}
正如你说看到了,重载+=时,需要重新开辟一个str1.length+str2.length+1大小的空间。
其实也没有什么好说的吧!
0 0
- 浅析C++中的重载运算符(重点是重载+=)
- C++(笔记)浅析运算符重载&实例
- 运算符重载(c++)
- 浅析Python运算符重载
- 【C++】String类中的运算符重载
- C++-运算符重载
- [C++]重载运算符
- C#:运算符重载
- c++-++运算符重载
- C++:重载运算符
- 运算符重载(C++)
- [c++]运算符重载
- 【C++】运算符重载
- C++--------------------------------------------运算符重载
- C#:运算符重载
- C++:运算符重载
- C++:运算符重载
- C#:运算符重载
- iOS 警告收录及科学快速的消除方法
- html中的简单实例演示(checkbox)的使用
- tomcat 多域名配置问题,context配置书写规范导致的jsp编译异常
- 判断是否是变形字符串
- CCDT与CDT
- 浅析C++中的重载运算符(重点是重载+=)
- C++之 构造函数 拷贝构造函数 析构函数 赋值操作
- genymotion的一个小错误
- 在Fragment 里面关于ViewPagerIndicator设置样式(Style)不起作用
- Lesson01UIView 用户界面
- 录制音频
- NoSQL数据库是否适用于非互联网行业
- bestcoder#58 Inversion 即 hdu5497 (树状数组维护逆序数)
- 开源分布式计算系统框架比较