C++/Java 中的运算符优先级

问题描述

我一直在深入了解面向对象编程中的运算符优先级。 代码如下:

             int a=5;
             int b=5;
             printf("Output %d",a++>b);
             return 0;

输出输出 0。

根据我的理解,一元运算符的优先级高于关系运算符。 所以a++>b不应该是6>5。这是真的。但代码输出 False。谁能解释一下为什么?

提前致谢。

解决方法

您得到 false 是因为您在执行 a++ 时使用了后缀增量运算符,在您的情况下会导致比较 5 > 5

后缀自增运算符可以这样想。注意:这是为了证明这一点而制作的非法代码:

class int {                 // if there had been an "int" class
    int operator++(int) {   // postfix increment 
        int copy = *this;   // make a copy of the current value
        *this = *this + 1;  // add one to the int object
        return copy;        // return the OLD value
    }
};

如果您使用了前缀增量运算符 ++a,您将得到比较 6 > 5 - 因此结果 true。可以这样考虑前缀增量运算符。再次,非法代码:

class int {
    int& operator++() {    // prefix increment
        *this = *this + 1; // add one to the int object
        return *this;      // return a reference to the actual object
    }
};