|
The type of the operand(s) determine whether an expression is legal and, if the expression is legal, determines the meaning of the expression. However, in C++(www.cppentry.com) some types are related to one another. When two types are related, we can use an object or value of one type where an operand of the related type is expected. Two types are related if there is a conversion between them.
As an example, consider - int ival = 0;
- ival = 3.541 + 3;
which assigns 6 to ival.
The operands to the addition operator are values of two different types: 3.541 is a literal of type double, and 3 is a literal of type int. Rather than attempt to add values of the two different types, C++(www.cppentry.com) defines a set of conversions to transform the operands to a common type before performing the arithmetic. These conversions are carried out automatically by the compiler without programmer intervention—and sometimes without programmer knowledge. For that reason, they are referred to as implicit type conversions.
隐式类型转换是C++(www.cppentry.com) 的难点之一。C++(www.cppentry.com) 从C 语言继承了复杂的隐式类型转换规则,这些规则不是每条都符合直觉。如果不熟悉这些规则,有可能造成意想不到的后果。
The built-in conversions among the arithmetic types are defined to preserve precision, if possible. Most often, if an expression has both integral and floatingpoint values, the integer is converted to floating-point. In this addition, the integer value 3 is converted to double. Floating-point addition is performed and the result, 6.541, is of type double.
The next step is to assign that double value to ival, which is an int. In the case of assignment, the type of the left-hand operand dominates, because it is not possible to change the type of the object on the left-hand side. When the left- and right-hand types of an assignment differ, the right-hand side is converted to the type of the left-hand side. Here the double is converted to int. Converting a double to an int truncates the value; the decimal portion is discarded. 6.541 becomes 6, which is the value assigned to ival. Because the conversion of a double to int may result in a loss of precision, most compilers issue a warning. For example, the compiler we used to check the examples in this book warns us: - warning: assignment to ‘int’ from ‘double’
To understand implicit conversions, we need to know when they occur and what conversions are possible.
|