您的位置:首页 > 运维架构

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

2016-03-18 13:42 253 查看
为什么这么写

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的引用,即就是它自己,它可以再次作为左值,因而能够连着写这个输出流 。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ostream