【问题标题】:Why doesn't this comparison to bool work for an istream?为什么这种与 bool 的比较不适用于 istream?
【发布时间】:2013-11-02 23:07:22
【问题描述】:

我对如何/为什么可以在条件句中使用 istream 的理解很脆弱。我读过这个问题:(Why istream object can be used as a bool expression?)。

我不明白为什么编译没有错误......

while (cin >> n) {
    // things and stuff
}

…虽然编译失败(消息error: invalid operands to binary expression ('int' and '__istream_type' (aka 'basic_istream<char, std::char_traits<char> >'))

while (true == (cin >> n)) {
    // things and stuff
}

【问题讨论】:

  • 这是哪个编译器?
  • libc++,我想。 (Xcode 和/或 CodeRunner)
  • 嗯,我主要担心的是它显示int 而不是bool。无论如何,应该有一个到bool 的显式转换运算符,但我认为还没有任何实现。
  • 是否在 c++11 模式下? operator bool 仅在 c++11 中添加。
  • 是的,c++11 模式。 (我也对int 感到困惑)

标签: c++ boolean istream


【解决方案1】:

因为cin的隐式转换运算符是

operator void*() const { ... }

它可以评估为零,所以你可以检查它是否为零

while (cin >> x) {}

bool 的转换运算符声明为 explicit,因此您的表达式不会调用它:

explicit operator bool(){ ... }

所以,你需要一个明确的演员表:

if (true == static_cast<bool>(cin >> a))
{
}

【讨论】:

  • 还有一个operator bool()
  • @0x499602D2,也可能有点多。它在 C++11 中更改explicit operator bool()
  • 有趣。我想我可能必须投,但不明白为什么。谢谢你。 (还不能接受答案。)
  • 你说'它只是用于测试0' 但是当 cin 读取为 0 时,该表达式的计算结果为真。那(你提到的 0)是否意味着 cin 从隐式转换中返回 NULL|nullptr
  • 我稍微编辑了那部分。欲了解更多信息,请阅读this。该运算符返回!fail()
【解决方案2】:

cin &gt;&gt; n 返回一个istream&amp;。因为结果用于比较,所以编译器搜索 operator==(bool, istream),但它找不到。因此,您会收到一条错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 2015-10-26
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    相关资源
    最近更新 更多