实作一个Input操作符,即重载操作符operator <<。原则同实作Output操作符相同,参看C++标准库笔记:13.12.1 实作一个Output操作符
下文代码所用测试类:
class Fraction
{
public:
Fraction( int nNumerator = 0, int nDemominator = 1 )
:m_nNumerator( nNumerator ), m_nDemominator( nDemominator )
{}
int Numerator() const { return m_nNumerator; }
int Demominator() const { return m_nDemominator; }
private:
int m_nNumerator; //分子
int m_nDemominator; //分母
};
简单实现,不检测出错状态,直接读出分数:
std::istream& operator >> ( std::istream& in, Fraction& f )
{
int n = 0, d = 1;
in >> n;
in.ignore(); //skip '/'
in >> d;
f = Fraction( n, d );
return in;
}
以上简单实现存在几个问题:
- 参数传送的是istream(
std::basic_istream<char>
),故对wchar_t就无能为力了。 - 未进行错误处理,读取错误应设置流的错误标志。
- 读取失败时,不应改变结果值(
Fraction& f
)。
以下代码解决了以上提到的问题(仅仅是演示而已,还有很多细节没考虑进去):
template <class charT, class traits>
inline std::basic_istream<charT, traits>&
operator >> ( std::basic_istream<charT, traits>& in, Fraction& f )
{
int n = 0, d = 1;
in >> n;
if ( in.peek() == '/' )
{
in.ignore();
in >> d;
}
//if denominator is zero
//set failbit as IO format error
if ( d == 0 )
{
in.setstate( std::ios::failbit );
return in;
}
//if everything is fine as far
//change the value of the fraction
if ( in )
{
f = Fraction( n, d );
}
return in;
}