【发布时间】:2015-02-04 06:03:57
【问题描述】:
最近我读了一些章节 C++ Primer,有一件事情让我很困惑。
书上说:
There are four operators that do guarantee the order in which operands are evaluated.
the logical AND (&&) operator,
the logical OR (||) operator,
the conditional (? :) operator,
and the comma (,) operator.
然后我看到了这些代码:
if (val == true) { /* ... */ } // true only if val is equal to 1!
然后书中解释:
If val is not a bool, then true is converted to the type of val before the == operator is applied.
That is, when val is not a bool, it is as if we had written
if (val == 1) { /* ... */ }
这是我的问题:
为什么将bool类型true转换为算术类型,而不是val?它是否涉及相等运算符的评估顺序?
正如书中所说,只有四个运算符保证顺序,不包括相等运算符。所以上面表达式的结果应该是未定义的,对吗?如果不是,应该是什么?
期待您的回复。提前致谢。
【问题讨论】:
-
你混淆了两个非常不同的东西。
true被转换为另一个参数的类型,因为在算术运算符中,较低等级的参数被转换为另一个参数的类型。与求值顺序无关。 -
如前所述(即脱离上下文),“如果 val 不是 bool,则在应用 == 运算符之前将 true 转换为 val 的类型。” 一般来说不正确,因为
val可能是具有operator bool() const成员的类的实例,然后将与true进行比较,而不涉及任何整数转换。
标签: c++ equality operator-precedence