c++ - std::cin 如何同时返回 bool 和自身?

标签 c++ cin

我正在读一本关于 C++ 的书,上面说如果我使用 >> 运算符,它会返回运算符左侧的对象,所以在这个例子中

std::cin >> value1;

代码返回std::cin

但如果我这样做

while(std::cin >> value1)

我的代码将一直在循环中,直到出现 std::cin 错误,所以这一定意味着运算符返回一个 bool,当 std::cin 失败时,std::cin 不会失败并且为 false。

是哪一个?

最佳答案

[...] 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 的上下文中,例如 ifwhile 循环和 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/

相关文章:

c++ - std::function 可以序列化吗?

c++ - (cin >> buf && !buf.empty()) 中的第二个条件是否多余?

c++ - 如何忽略标准输入的下一个整数

c++ - 当我不需要 C++ 计算时如何忽略某些输入?

c++ - 当找不到分隔符时,如何阻止 cin.getline() 导致控制台重复获取用户输入?

c++ - Mysql.h C++ 参数过多

c++ - 创建多个 Caffe 实例 - C++

c++ - std::cin 可以在运行时从接受文件输入切换到键盘输入吗?

c++ - 在 Qt 5.3 中向工具栏添加图标

c++ - 模板对象可以改变它的类型吗?