c++ - 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
}
};
推荐阅读
- unity3d - 如何绘制路径轨迹像下面的游戏参考统一
- microcontroller - 使用 UART 同步两个微控制器之间的串行通信的最佳方法是什么?
- php - 如何在codeigniter中限制同一用户多次登录另一个系统
- google-cloud-platform - 将子域重定向到谷歌云
- php - Laravel 6 - Illuminate\Database\Eloquent\RelationNotFoundException 调用未定义的关系
- php - “错误:插入”非特定插入错误
- ios - 如何在 Xcode UI 测试中获得授权部分
- php - GROUP_BY 中的错误,查询来自两个数据库 CODEIGNITER
- regex - 参数扩展正则表达式?
- c - 在使用递归函数调用时何时使用'return'?