注册 登录
编程论坛 C++教室

这样的格式对吗?

ddsxd 发布于 2007-04-04 22:53, 429 次点击
书上的一个操作符重载的函数,是一个表示日期的类的输出流函数。原文如下:

ostream& operator<<(ostream& o, const Date& d){
o<<setfill('0')<<setw(4)<<d.year<<'-'<<setw(2)<<d.month<<'-';
return o<<setw(2)<<d.day<<'\n'<<setfill(' ');
}//------------------------------------

我感觉是印刷错误,应该是
ostream& operator<<(ostream& o, const Date& d){
o<<setfill('0')<<setw(4)<<d.year<<'-'<<setw(2)<<d.month<<'-'<<setw(2)<<d.day<<'\n'<<setfill(' ');
return o;
}//------------------------------------

结果一运行,两种写法都对,运行结果一样。
函数碰到return不就返回了吗?怎么还可以输出后面的内容啊,而且也没见过这种语句格式,挺不能理解的,有没有人能解释一下啊?



[此贴子已经被作者于2007-4-4 22:54:44编辑过]

2 回复
#2
wfpb2007-04-05 09:55
o<<setfill('0')<<setw(4)<<d.year<<'-'<<setw(2)<<d.month<<'-';
o<<setw(2)<<d.day<<'\n'<<setfill(' ');
本来就等价于
o<<setfill('0')<<setw(4)<<d.year<<'-'<<setw(2)<<d.month<<'-'<<setw(2)<<d.day<<'\n'<<setfill(' ');
return执行的时候是return右边的语句执行完后的o
#3
ddsxd2007-04-05 21:59
O 谢谢斑竹
1