如何重载流操作符
为自己的类定义插入符和提取符,就是重载相关运算符:
* 第一个参数定义成流的非const引用
* 执行插入或提取的操作
* 返回流的引用
流应该为非常量,因为处理数据将改变流的状态.通过返回流,可以将多个流操作连接成一条语句.
例子,插入符重载
考虑输出MM-DD-YYYY格式的Date对象:
ostream& operator<<(ostream& os, const Date& d)
{
char fillChar = os.fill('0');//设置填充字符,保存原有填充字符
os << setw(2) << d.getMonth() << '-' //设置域宽
<< setw(2) << d.getDay() << '-'
<< setw(4) << setfill(fillChar) << d.getYear();//回复原有填充字符
return os;
}
这个函数不能设为Data类的成员函数,因为左操作数必须是流对象.
例子,提取符重载
使用提取符需要注意输入数据错误的情况:
istream& operator>>(istream& is, Date& d)
{
is >> d.month;
char dash;
is >> dash;
if (dash != '-') is.setstate(ios::failbit);
is >> d.day;
is >> dash;
if (dash != '-') is.setstate(ios::failbit);
is >> d.year;
return is;
}
通过设置流的失败标志位可以表明流产生了错误,一旦标志位被设置,在流恢复到有效状态之前,所有流操作都会被忽略.