简体   繁体   English

显式/隐式类型转换c ++

[英]explicit/implicit type conversion c++

I have a line of code 我有一行代码

double i = 1 + (long)1.5* 5.0f

My question is what is the conversion order and the result? 我的问题是转换顺序和结果是什么? Been searching for examples like this, but to no avail. 一直在寻找这样的例子,但无济于事。 Any good guides out there that may help me understand it? 有什么好的指南可以帮助我理解它吗?

My question is what is the conversion order and the result? 我的问题是转换顺序和结果是什么?

The cast is applied to 1.5 , giving a long with value 1 . 强制转换应用于1.5 ,给出long1

That's converted to float for multiplication with 5.0f , giving a float with value 5.0f . 这被转换为float乘以5.0f ,给出一个值为5.0ffloat

1 is converted to float for addition with that value, giving a float with value 6.0f . 1转换为float用于添加与该值,得到float值为6.0f

Finally, that's promoted to double (retaining the value 6.0 ) to assign to i . 最后,这被提升为double (保留值6.0 )以分配给i

This assumes a non-crazy floating point format that can represent small integers exactly; 这假设一种非疯狂的浮点格式,可以准确地表示小整数; otherwise, there may be rounding errors. 否则,可能存在舍入错误。

If you wanted to cast the result of the multiplication, then use parentheses to control the operator precedence: 如果要转换乘法的结果,则使用括号来控制运算符优先级:

double i = 1 + (long)(1.5* 5.0f);  // = 8.0

or use a C++-style cast, which forces the use of parentheses: 或使用C ++风格的强制转换,强制使用括号:

double i = 1 + static_cast<long>(1.5* 5.0f)

Any good guides out there that may help me understand it? 有什么好的指南可以帮助我理解它吗?

Here's one: http://en.cppreference.com/w/cpp/language/operator_precedence . 这是一个: http//en.cppreference.com/w/cpp/language/operator_precedence Note that the type cast has a higher precedence than multiplication, which is in turn higher than addition (3 vs. 5 vs. 6). 请注意,类型转换具有比乘法更高的优先级,而乘法又高于加法(3对5对6)。

这个表中可以看出,强制转换操作符的优先级高于乘法,但请遵循建议使用括号。

This precedence table should tell you everything you need to know. 此优先级表应告诉您需要知道的所有内容。

  1. Casting: 1.5 is cast to a long 施法: 1.5施放到long
  2. Multiplication: 1.5 * 5.0f , which casts this product as a float 乘法: 1.5 * 5.0f ,将此产品转换为float
  3. Addition: 1 + ( ((long) 1.5) * 5.0f) 增加: 1 + ( ((long) 1.5) * 5.0f)
  4. Assignment: i = 1 + ((long) 1.5 * 5.0f) 作业: i = 1 + ((long) 1.5 * 5.0f)

If you're not sure what the precedence of the casting operator is then rewrite the expression (in your head) 如果您不确定转换运算符的优先级是什么,那么重写表达式(在您的头脑中)

(long)1.5 * 5.0

to

5.0 * (long)1.5

Here its pretty obvious what has precedence and its the same with the first version 这里显而易见的是优先级和第一个版本相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM