【发布时间】:2015-06-03 18:40:52
【问题描述】:
这是关于用户编写的 C++ 输入流提取运算符 (>>) 的哲学(规范设计)的问题。
假设在进入 >> 运算符实现时(对于用户编写的类),已经为输入流设置了 eof 标志。
应该是用户编写的提取操作符(>>)
- 设置失败标志(因为找不到所需对象的实例)
- 是否应该在仍设置了 eof 标志的情况下返回给调用方。
如果使用第二种方法,则意味着调用者必须始终检查 eof 标志,然后再尝试调用 >> 运算符。原因是 >> 运算符可能会成功提取所需类的实例并设置 eof 标志。
原始代码如下。根据下面的 cmets,此代码似乎是错误的。如果 eof 已在输入中设置,则提取运算符将简单地返回,但仍设置 eof。似乎如果设置了 eof,但未设置 bad 和 fail,则应提取字符串以设置失败位。当然也可以直接设置fail bit。
/* Implement the C/C++ >> (stream input) operator as a non-member
function */
std::istream &operator>>(std::istream& is, DecNumber &val) {
DecContext context{DecContext::defInit};
uint32_t status;
/* The true value below prevents whitespace from being skipped */
std::istream::sentry s(is, true);
std::string inStr;
/* Check if the input stream is in a good state. Just return to the
caller if the input stremm is not in a good state. The caller
must handle this condition. */
if(!s)
return is;
/* Get a string from the input stream. This string is converted to
a DecNumber below. Just return to the caller if this step causes
any stream related errors. Note that reaching the end of the
input is not a stream related error here. A decimal number might
be the absolute last thing in the stream. */
is >> inStr;
if (is.bad() || is.fail())
return is;
/* Try to convert the string to a DecNumber using the default context
value */
decNumberFromString(val.getDecVal(), inStr.c_str(), context.getDecCont());
status = context.DecContextGetStatus();
/* Remove a few status bits we don't care about */
status &= ~(DEC_Inexact + DEC_Rounded);
if (status)
is.setstate(std::ios_base::failbit);
return is;
}
【问题讨论】:
-
写一个concise sample 来澄清你真正想要的是什么!如前所述,我已经用尽了我对这个问题的密切投票,但除非你在你的问题中表明这一点,否则它要么过于宽泛,要么实际上基于意见。
-
πάντα ῥεῖ,我的目的是获得有关流提取运算符 (>>) 的规范形式如何处理在输入时存在或在提取过程中发生的 eof 条件的建议.许多人(包括您)对解决这个问题非常有帮助。
-
没有规范的形式,但用例可以用于自定义重载。抱歉,c++ 不提供烹饪食谱,而是提供灵活性。
标签: c++ overloading operator-keyword