operator 与&operator
2015-06-04 23:41
357 查看
之前一直搞不懂operator 与&operator的区别。
简单来说就是operator 返回的是这个值,而&operator返回的是这个的地址。
主要的区别于用处就在于这个运算符的连用性,如果需要连用的话必须使用引用。
看了下别人的理解了下:
如果写成这样
ostream operator << (ostream& os, Point& pt)
则:
Point a, b;
cout<<a<<b;
错误,只能写为:
cout<<a;
cout<<b;
原因在于
cout<<a<<b;
相当于:
(cout<<a)<<b;
第一个()中返回cout的临时变量,它不可以作为左值(因为operator << (ostream& os, Point& pt)的第一个参数是ostream&,而不是ostream),因而错误。
如果写成:
ostream& operator << (ostream& os, Point& pt)
则:
cout<<a<<b;
正确,因为它等同于
(cout<<a)<<b;
(cout<<a)返回cout的引用,即就是它自己,它可以再次作为左值,因而能够连着写这个输出流 。
简而言之就是&operator可以将这个运算符连用。
测试程序:
简单来说就是operator 返回的是这个值,而&operator返回的是这个的地址。
主要的区别于用处就在于这个运算符的连用性,如果需要连用的话必须使用引用。
看了下别人的理解了下:
如果写成这样
ostream operator << (ostream& os, Point& pt)
则:
Point a, b;
cout<<a<<b;
错误,只能写为:
cout<<a;
cout<<b;
原因在于
cout<<a<<b;
相当于:
(cout<<a)<<b;
第一个()中返回cout的临时变量,它不可以作为左值(因为operator << (ostream& os, Point& pt)的第一个参数是ostream&,而不是ostream),因而错误。
如果写成:
ostream& operator << (ostream& os, Point& pt)
则:
cout<<a<<b;
正确,因为它等同于
(cout<<a)<<b;
(cout<<a)返回cout的引用,即就是它自己,它可以再次作为左值,因而能够连着写这个输出流 。
简而言之就是&operator可以将这个运算符连用。
测试程序:
#include <iostream> using namespace std; //定义点类 class Point { public: int x,y; Point(){} Point(int xx,int yy){x=xx;y=yy;} void print(){ cout<<"("<<x<<","<<y<<")\n"; } friend Point &operator+(Point &a,Point &b); //friend Point operator+(Point &a,Point &b); }; //重载+号操作(返回值) /*Point operator+( Point &a,Point &b) { Point s(a.x+b.x,a.y+b.y); return s; }*/ //重载+号操作(返回址) Point &operator+( Point &a,Point &b) { a.x+=b.x; a.y+=b.y; return a; } //主函数 int main() { Point a(3,2),b(1,5),c(1,6),e; e=c+a+b; //如果没有取地址的话不能进行连加操作 e.print(); }
相关文章推荐
- Linux 环境下开发 常用指令
- 一、文件安全与权限
- Linux 常用命令
- centos上编译的可执行程序在suse上无法运行
- OpenGL绘制旋转立方体实例
- 微信公众号运营人员必备的软件工具网站合集
- Linux常用命令-文件处理命令-文件处理命令
- Tomcat优化配置
- 关于LINUX C中函数strtok使用要点
- 在CentOS上使用Neatbeans开发C++,调用Python的过程、遇到的问题和解决办法
- Docker 使用方法总结之:管理工具 shipyard 的详细使用指南
- linux配置java环境变量(详细) [转]
- DEVICE_ATTR
- nginx相关内容的备份
- 浅谈Unix/linux下的内存管理
- Linux查看及设置系统时区
- Linux查看及设置系统时区
- Myeclipse 自带Tomcat没有欢迎页面
- 『PHP』网站速度变慢综合问题汇总
- linux目录概述