设为首页 加入收藏

TOP

5.12.6 Named Casts (1)
2013-10-07 15:24:29 来源: 作者: 【 】 浏览:61
Tags:5.12.6 Named Casts

The general form for the named cast notation is the following:

  1. cast-name<type>(expression); 

cast-name may be one of static_cast, const_cast, dynamic_cast, or reinterpret_cast. type is the target type of the conversion, and expression is the value to be cast. The type of cast determines the specific kind of conversion that is performed on the expression.

如果程序里确实需要显式转换,那么应该用这四个具名操作符。

  1. dynamic_cast 

A dynamic_cast supports the run-time identification of objects addressed either by a pointer or reference. We cover dynamic_cast in Section 18.2 (p. 772).

  1. const_cast 

A const_cast, as its name implies, casts away the constness of its expression. For example, we might have a function named string_copy that we are certain reads, but does not write, its single parameter of type char*. If we have access to the code, the best alternative would be to correct it to take a const char*. If that is not possible, we could call string_copy on a const value using a const_cast:

  1. const char *pc_str;  
  2. char *pc = string_copy(const_cast<char*>(pc_str)); 

Only a const_cast can be used to cast away constness. Using any of the other three forms of cast in this case would result in a compile-time error. Similarly, it is a compile-time error to use the const_cast notation to perform any type conversion other than adding or removing const.

  1. static_cast 

Any type conversion that the compiler performs implicitly can be explicitly requested by using a static_cast:

  1. double d = 97.0;  
  2. // cast specified to indicate that the conversion is intentional  
  3. char ch = static_cast<char>(d); 

Such casts are useful when assigning a larger arithmetic type to a smaller type. The cast informs both the reader of the program and the compiler that we are aware of and are not concerned about the potential loss of precision. Compilers often generate a warning for assignments of a larger arithmetic type to a smaller type. When we provide the explicit cast, the warning message is turned off.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇5.12.6 Named Casts (2) 下一篇5.8 The sizeof Operator

评论

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

·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)