|
One reason to perform an explicit cast is to override the usual standard conversions. The following compound assignment - double dval;
- int ival;
ival *= dval;
converts ival to double in order to multiply it by dval. That double result is then truncated to int in order to assign it to ival. We can eliminate the unnecessary conversion of ival to double by explicitly casting dval to int:
注意:这实际上改变了程序的行为。若初值ival== 2 且 dval == 2.75,第一种写法的结果是ival == 5,而第二种写法先将dval 转换为整数2,则ival == 4。 - ival *= static_cast<int>(dval);
Another reason for an explicit cast is to select a specific conversion whenmore than one conversion is possible. We will look at this case more closely in Chapter 14.
|