微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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
    }
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。