如何将“>>”重载为复数输入形式?
重载“>>”运算符,输入格式为:a+bi,其中a, b分别为实部和虚部。
你参考一下 operator>>( ……,std::complex ) 的实现,它允许 -123、(-123),(-123, 456) 等复数形式,若有符号,符号首先出现。
程序代码:template <class _Ty, class _Elem, class _Tr>
basic_istream<_Elem, _Tr>& operator>>(basic_istream<_Elem, _Tr>& _Istr, complex<_Ty>& _Right)
{
const ctype<_Elem>& _Ctype_fac = _STD use_facet<ctype<_Elem>>(_Istr.getloc());
_Elem _Ch = 0;
long double _Real = 0;
long double _Imag = 0;
if (_Istr >> _Ch && _Ch != _Ctype_fac.widen('(')) { // no leading '(', treat as real only
_Istr.putback(_Ch);
_Istr >> _Real;
_Imag = 0;
} else if (_Istr >> _Real >> _Ch && _Ch != _Ctype_fac.widen(',')) {
if (_Ch == _Ctype_fac.widen(')')) {
_Imag = 0; // (real)
} else { // no trailing ')' after real, treat as bad field
_Istr.putback(_Ch);
_Istr.setstate(ios_base::failbit);
}
} else if (_Istr >> _Imag >> _Ch && _Ch != _Ctype_fac.widen(')')) { // no imag or trailing ')', treat as bad field
_Istr.putback(_Ch);
_Istr.setstate(ios_base::failbit);
}
if (!_Istr.fail()) { // store valid result
_Ty _Tyreal(static_cast<_Ty>(_Real)), _Tyimag(static_cast<_Ty>(_Imag));
_Right = complex<_Ty>(_Tyreal, _Tyimag);
}
return _Istr;
}






