5.12.1 When Implicit Type Conversions Occur

2013-10-07 15:24:00 · 作者: · 浏览: 75

尽管我们在写代码时应该避免隐式或显式的类型转换,但是有些转换是在不经意间发生的。读者应该熟悉发生隐式类型转换的五种场景。

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:

  1. int ival;  
  2. double dval;  
  3. ival >= dval // ival converted to double 

· An expression used as a condition is converted to bool:

  1. int ival;  
  2. if (ival) // ival converted to bool  
  3. 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:

  1. int ival = 3.14; // 3.14 converted to int  
  2. int *ip;  
  3. 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.