【问题标题】:Two comparison operators in c++ like pythonc ++中的两个比较运算符,如python
【发布时间】:2017-12-22 08:57:51
【问题描述】:

比较 5 > x > 1 在 C++ 中是否像在 python 中一样工作。它没有显示任何编译错误,但似乎也不起作用。

【问题讨论】:

  • 它工作正常。你能举一个失败的例子吗?
  • ((795 > x > 4) && (595 > y > 4)) 即使 (x,y) 为 (400,300),此条件也会返回 false
  • @GarbageCollector 问题不在于它是否工作很好,问题是它是否像在 python 中一样工作,答案是明确的“不"。
  • @Zinki 你能详细说明这两种语言的工作方式的区别吗?
  • @Vikramark:下面 Bathsheba 的回答使这个特殊案例的区别非常清楚。如果您想了解一般情况下语言之间的使用差异,这有点超出了这个问题的范围,但是对于从一种语言到另一种语言的程序员来说,可能有一些很好的介绍性资源。

标签: python c++ logic comparison-operators


【解决方案1】:

在 C++ 中,5 > x > 1 被分组为 (5 > x) > 1

(5 > x)falsetrue,因此它永远不会大于1,因为falsetrue 分别转换为01。因此

5 > x > 1

在 C++ 中是 false,对于 x 的任何值。所以在 C++ 中你需要用更长的形式写出你真正想要的表达式

x > 1 && x < 5

【讨论】:

    【解决方案2】:

    我对 you can't 选项永远不满意...所以理论上 你可以 像这样重载运算符(只是一个草图,但我想你会得到重点):

    #include <iostream>
    
    template <class T>
    struct TwoWayComparison {
        T value;
        bool cond = true;
    
        friend TwoWayComparison operator >(const T& lhs, const TwoWayComparison& rhs) {
            return {rhs.value, lhs > rhs.value};
        }
        friend TwoWayComparison operator >(const TwoWayComparison& lhs, const T& rhs) {
            return {rhs, lhs.cond && lhs.value > rhs};
        }
        operator bool() {
            return cond;
        }
    };
    
    int main() {
        TwoWayComparison<int> x{3};
        if (15 > x > 1) {
            std::cout << "abc" << std::endl;
        }
    }
    

    [live demo]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      相关资源
      最近更新 更多