我正在读一本关于 C++ 的书,上面说如果我使用 >> 运算符,它会返回运算符左侧的对象,所以在这个例子中
std::cin >> value1;
代码返回std::cin
。
但如果我这样做
while(std::cin >> value1)
我的代码将一直在循环中,直到出现 std::cin
错误,所以这一定意味着运算符返回一个 bool
,当 当
不会失败并且为 false。std::cin
失败时,std::cin
是哪一个?
最佳答案
[...] so that must mean that the operator returns a bool [...]
不,它返回 std::cin
(通过引用)。 while(std::cin >> value);
之所以起作用是因为 std::istream
(这是 std::cin
) 有一个 conversion operator .
一个转换操作符基本上允许一个类被隐式地(如果它没有被标记为explicit
)被转换成一个给定的类型。在这种情况下,std::istream
定义了它的operator bool
来返回是否发生了错误(通常是failbit
);
[std::ios_base::operator bool()]
Returns
true
if the stream has no errors and is ready for I/O operations. Specifically, returns!fail()
.
explicit operator bool() const;
请注意,即使运算符是 explicit
(它不应该允许像 if (std::cin);
这样的隐式转换),使用时也会忽略限定符在需要 bool
的上下文中,例如 if
、while
循环和 for
循环。不过,这些是异常(exception),而不是规则。
这是一个例子:
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
关于c++ - std::cin 如何同时返回 bool 和自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38978266/