这么写ostream& operator << (ostream& os, Point& pt)而不写成ostream operator << (ostream& os, Point& pt)

来源:互联网 发布:acm算法视频百度云 编辑:程序博客网 时间:2024/06/06 01:33

为什么这么写
ostream& operator << (ostream& os, Point& pt)
而不写成
ostream operator << (ostream& os, Point& pt)
ostream&这个返回值类型用定义成别名的形式吗??

在网上找到了答案如下:

如果写成这样
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的引用,即就是它自己,它可以再次作为左值,因而能够连着写这个输出流 。


1 0
原创粉丝点击