《C++ Primer 第五版》第14章讨论了类型转换操作符:
Under earlier versions of the standard, classes that wanted to define a conversion to bool faced a problem: Because bool is an arithmetic type, a class-type object that is converted to bool can be used in any context where an arithmetic type is expected.
Such conversions can happen in surprising ways. In particular, if istream had a conversion to bool, the following code would compile:
int i = 42; cin << i; // this code would be legal if the conversion to bool were not explicit!
This program attempts to use the output operator on an input stream. There is no
<<
defined foristream
, so the code is almost surely in error. However, this code could use the bool conversion operator to convertcin
tobool
. The resulting bool value would then be promoted to int and used as the left-hand operand to the built-in version of the left-shift operator. The promoted bool value (either 1 or 0) would be shifted left 42 positions.
输入流可以转换为布尔值,表示流的内部状态(成功或失败)。我们过去常做:
while(std::cin >> str)...
那么为什么这段代码不会编译呢?
int x = 0;
std::cin << x;
如果我使用显式转换,它就有效:
(bool)cin << 5; // works although bad
if (std::cin >> x)
也是允许的,就像我在上面链接的问答中解释的那样。 - 463035818_is_not_a_numberwhile (cin >> val)
将返回一个流,然后会转换为类似指针的对象,它是整数类型,因此可以用于强制退出循环。旧时光荣岁月真是有趣。 - Martin York