【问题标题】:Weird boolean conversion (?)奇怪的布尔转换(?)
【发布时间】:2014-05-29 18:34:50
【问题描述】:

请解释为什么第二个表达式返回 false

   cout << (4==4) << endl; //1
   cout << (4==4==4) << endl; // 0

【问题讨论】:

    标签: c++


    【解决方案1】:

    (4==4==4) 基本上是((4==4)==4) 这是(true == 4) 这是(1==4) 1 这是false 2 这是打印为0 .

    请注意,== 具有关联性 left-to-right,但这并不重要(在 这种 情况下),因为即使它具有从右到左的关联性,结果也会是相同的。


    1.由于积分促销。
    2.请注意,有人可能会认为(true==4) 中的4 可以被视为true(毕竟4 不为零,因此true)。这种想法可能会得出结论(true==4)(true==true)true。但这不是它的工作方式。是 bool 被提升为 int,而不是 int 被提升为 bool。

    【讨论】:

    • 那我如何比较 3 个元素呢?
    • @OrangeFox: if ((x == 4) &amp;&amp; (y == 4))
    • 它被称为promotion 是有原因的;你统一到更一般的类型
    • @ScarletAmaranth:是的。 :-)
    • @MooingDuck:如何避免递归,而使用迭代呢? coliru.stacked-crooked.com/a/d6d9d3cca1c0839d ...只是它使用数组;我们可以避免这种情况,减少堆栈使用和副本吗?
    【解决方案2】:

    4==4 的计算结果为true,为了与4 进行比较,它被转换为11 == 4false,也就是0

    【讨论】:

      【解决方案3】:

      您不能合理地将二元比较运算符应用于两个以上的运算符(除非您有覆盖使其成为可能,以某种方式)。

      比较未知数量的参数:

      #include <iostream>
      
      template <typename A, typename B>
      bool equal(const A& a, const B& b) {
          return a == b;
      }
      
      template <typename A, typename B, typename ... Other>
      bool equal(const A& a, const B& b, const Other& ... other) {
          return a == b && equal(b, other ...);
      }
      
      int main() {
          std::cout << equal(1, 1, 1) << '\n';
          std::cout << equal(1, 2, 3) << '\n';
      }
      

      C++ 11

      【讨论】:

      • ewww;不要在此处强加 可复制;通过 const ref 获取;您只需要 equality_comparable
      猜你喜欢
      • 2011-07-15
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      相关资源
      最近更新 更多