之前一直搞不懂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可以将这个运算符连用。
测试程序:
#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();
}