尽管我们在写代码时应该避免隐式或显式的类型转换,但是有些转换是在不经意间发生的。读者应该熟悉发生隐式类型转换的五种场景。
The compiler applies conversions for both built-in and class type objects as necessary. Implicit type conversions take place in the following situations:
· In expressions with operands of mixed types, the types are converted to a common type:
- int ival;
- double dval;
· An expression used as a condition is converted to bool:
- int ival;
- if (ival) // ival converted to bool
- while (cin) // cin converted to bool
Conditions occur as the first operand of the conditional ( :) operator and as the operand(s) to the logical NOT (!), logical AND (&&), and logical OR (||) operators. Conditions also appear in the if, while, for, and do while statements. (We cover the do while in Chapter 6)
· An expression used to initialize or assign to a variable is converted to the type of the variable:
- int ival = 3.14; // 3.14 converted to int
- int *ip;
- ip = 0; // the int 0 converted to a null pointer of type int *
In addition, as we’ll see in Chapter 7, implicit conversions also occur during function calls.