首页 > 解决方案 > C++/Java 中的运算符优先级

问题描述

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

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

输出为输出 0。

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

先感谢您。

标签: c++operator-keywordoperator-precedence

解决方案


你得到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
    }
};

推荐阅读