Team LiB
Previous Section Next Section

Chapter Summary

小结

C++ provides a rich set of operators and defines their meaning when applied to values of the built-in types. Additionally, the language supports operator overloading, which allows us to define the meaning of the operators for class types. We'll see in Chapter 14 how to define operators for our own types.

C++ 提供了丰富的操作符,并定义了用于内置类型值时操作符的含义。除此之外,C++ 还支持操作符重载,允许由程序员自己来定义用于类类型时操作符的含义。我们将在第十四章中学习如何重载自定义的操作符。

To understand compound expressionsexpressions involving more than one operatorit is necessary to understand precedence, associativity, and order of operand evaluation. Each operator has a precedence level and associativity. Precedence determines how operators are grouped in a compound expression. Associativity determines how operators at the same precedence level are grouped.

要理解复合表达式(即含有多个操作符的表达式)就必须先了解优先级、结合性以及操作数的求值次序。每一个操作符都有自己的优先级别和结合性。优先级规定复合表达式中操作符结合的方式,而结合性则决定同一个优先级的操作符如何结合。

Most operators do not specify the order in which operands are evaluated: The compiler is free to evaluate either the left- or right-hand operand first. Often, the order of operand evaluation has no impact on the result of the expression. However, if both operands refer to the same object and one of the operands changes that object, then the program has a serious bugand a bug that may be hard to find.

大多数操作符没有规定其操作数的求值顺序:由编译器自由选择先计算左操作数还是右操作数。通常,操作数的求值顺序不会影响表达式的结果。但是,如果操作符的两个操作数都与同一个对象相关,而且其中一个操作数改变了该对象的值,则程序将会因此而产生严重的错误——而且这类错误很难发现。

Finally, it is possible to write an expression that is given one type but where a value of another type is required. In such cases, the compiler will automatically apply a conversion (either built-in or defined for a class type) to transform the given type into the type that is required. Conversions can also be requested explicitly by using a cast.

最后,可以使用某种类型编写表达式,而实际需要的是另一类型的值。此时,编译器自动实现类型转换(既可以是内置类型也可以是为类类型而定义的),将特定类型转换为所需的类型。C++ 还提供了强制类型转换显式地将数值转换为所需的数据类型。

Team LiB
Previous Section Next Section