std :: cin如何同时返回布尔值和自身? [英] How can std::cin return a bool and itself at the same time?
问题描述
我正在阅读一本有关C ++的书,其中说如果使用>>运算符,它将返回该运算符左侧的对象,因此在此示例中
I'm reading a book on C++ that says that if I use the >> operator it returns the object at the left side of the operator so in this example
std::cin >> value1;
代码返回 std :: cin
.
但是如果我这样做
while(std::cin >> value1)
我的代码将一直处于循环状态,直到出现 std :: cin
错误,这必须表示操作员返回了 bool
,当std :: cin
不会失败,并且当 std :: cin
失败时为false.
My code will be in the loop until there is a std::cin
error so that must mean that the operator returns a bool
that is true when std::cin
does not fail and false when std::cin
fails.
是哪个?
推荐答案
[...],因此必须表示操作员返回布尔值[...]
[...] so that must mean that the operator returns a bool [...]
不是,它返回 std :: cin
(通过引用). while(std :: cin>>值);
起作用的原因是因为 std :: istream
(这是 std :: cin的类型
)具有 转换操作符 .
Nope, it returns std::cin
(by reference). The reason why while(std::cin >> value);
works is because std::istream
(which is the type of std::cin
) has a conversion operator.
转换运算符基本上允许将一个隐式类(如果未标记为 explicit
)转换为给定类型.在这种情况下, std :: istream
定义其 operator bool
来返回是否发生错误(通常为 failbit
);
A conversion operator basically permits a class to be implicitly (if it is not marked explicit
) to be converted to a given type. In this case, std::istream
defines its operator bool
to return whether an error (typically failbit
) occurred;
[std :: ios_base :: operator bool()]
如果流没有错误并且可以进行I/O操作,则返回
true
.具体来说,返回!fail()
.
explicit operator bool() const;
请注意,即使运算符是 explicit
(不允许像 if(std :: cin);
这样的隐式转换),使用限定符也会被忽略在需要 bool
的上下文中,例如 if
, while
循环和 for
循环.但这是例外,不是规则.
Note than even though the operator is explicit
(which shouldn't allow implicit conversions like if (std::cin);
), the qualifier is ignored when used in a context that requires a bool
, like if
, while
loops and for
loops. Those are exceptions though, not rules.
这里是一个例子:
if (std::cin >> value); //OK, a 'std::istream' can be converted into a 'bool', which
//therefore happens implicitly, without the need to cast it:
if (static_cast<bool>(std::cin >> value)); //Unnecessary
bool b = std::cin >> value; //Error!! 'operator bool' is marked explicit (see above), so
//we have to call it explicitly:
bool b = static_cast<bool>(std::cin >> value); //OK, 'operator bool' is called explicitly
这篇关于std :: cin如何同时返回布尔值和自身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!