设为首页 加入收藏

TOP

5.12 Type Conversions
2013-10-07 15:25:33 来源: 作者: 【 】 浏览:66
Tags:5.12 Type Conversions

The type of the operand(s) determine whether an expression is legal and, if the expression is legal, determines the meaning of the expression. However, in C++(www.cppentry.com) some types are related to one another. When two types are related, we can use an object or value of one type where an operand of the related type is expected. Two types are related if there is a conversion between them.

As an example, consider

  1. int ival = 0;  
  2. ival = 3.541 + 3; // typically compiles with a warning 

which assigns 6 to ival.

The operands to the addition operator are values of two different types: 3.541 is a literal of type double, and 3 is a literal of type int. Rather than attempt to add values of the two different types, C++(www.cppentry.com) defines a set of conversions to transform the operands to a common type before performing the arithmetic. These conversions are carried out automatically by the compiler without programmer intervention—and sometimes without programmer knowledge. For that reason, they are referred
to as implicit type conversions.

隐式类型转换是C++(www.cppentry.com) 的难点之一。C++(www.cppentry.com) 从C 语言继承了复杂的隐式类型转换规则,这些规则不是每条都符合直觉。如果不熟悉这些规则,有可能造成意想不到的后果。

The built-in conversions among the arithmetic types are defined to preserve precision, if possible. Most often, if an  expression has both integral and floatingpoint values, the integer is converted to floating-point. In this addition, the integer value 3 is converted to double. Floating-point addition is performed and the result, 6.541, is of type double.

The next step is to assign that double value to ival, which is an int. In the case of assignment, the type of the left-hand operand dominates, because it is not possible to change the type of the object on the left-hand side. When the left- and right-hand types of an assignment differ, the right-hand side is converted to the type of the left-hand side. Here the double is converted to int. Converting a double to an int truncates the value; the decimal portion is discarded. 6.541 becomes 6, which is the value assigned to ival. Because the conversion of a double to int may result in a loss of precision, most compilers issue a warning. For example, the compiler we used to check the examples in this book warns us:

  1. warning: assignment to ‘int’ from ‘double’ 

To understand implicit conversions, we need to know when they occur and what conversions are possible.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇5.12.4 Explicit Conversions 下一篇5.1 Arithmetic Operators (2)

评论

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

·Java后端面试实习自 (2025-12-25 09:24:21)
·Java LTS版本有哪些 (2025-12-25 09:24:18)
·2025年,JAVA还值得 (2025-12-25 09:24:16)
·用 C 语言或者限制使 (2025-12-25 08:50:05)
·C++构造shared_ptr为 (2025-12-25 08:50:01)