设为首页 加入收藏

TOP

5.12.5 When Casts Might Be Useful
2013-10-07 15:24:02 来源: 作者: 【 】 浏览:74
Tags:5.12.5 When Casts Might Useful

One reason to perform an explicit cast is to override the usual standard conversions. The following compound assignment

  1. double dval;  
  2. int ival;  
  3. ival *= dval; // 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。

  1. ival *= static_cast<int>(dval); // converts dval to int  

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.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇5.11 The new and delete Express.. 下一篇5.12.1 When Implicit Type Conve..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Sphinx : 高性能SQL (2025-12-24 10:18:11)
·Pandas 性能优化 - (2025-12-24 10:18:08)
·MySQL 索引 - 菜鸟教 (2025-12-24 10:18:06)
·Shell 基本运算符 - (2025-12-24 09:52:56)
·Shell 函数 | 菜鸟教 (2025-12-24 09:52:54)