是什么铸造和胁迫之间的区别? [英] What is the difference between casting and coercing?

查看:249
本文介绍了是什么铸造和胁迫之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了这两个术语在各种网上的解释几乎可以互换使用,大部分课本,我咨询了也是不看好的区别完全清楚。

有没有这也许可以解释的差异清晰简单的方式,你们知道吗?


  

类型转换(有时也称为类型转换


  
  

要在期望另一个上下文中使用一种类型的值。


  
  

Nonconverting类型转换(有时也被称为型的双关语


  
  

这一变化不会改变底层位。


  
  

强制


  
  

过程,通过该编译器将一种类型的值自动转换成当由周围的环境要求第二类型另一种类型的值。



解决方案

类型转换


  

转换指的是从一种数据类型或隐或显式地改变一个值到另一个,例如一个16位的整数为32位整数。


  
  

强制用来表示一个隐式转换。


  
  

通常是指一个显式类型转换(相对于隐式转换),无论这是否是一个位模式还是真正的重新间pretation转换。


所以,胁迫是隐含的,演员是明确的,并且转换其中任何一个。


几个例子(从相同的源):

强制(隐含的):

 双D;
INT I;
如果(d取代;ⅰ)D = 1;

CAST(明确的):

 双达3.3 =;
双DB = 3.3;
双DC = 3.4;
INT结果=(int)的DA +(INT)DB +(INT)直流电; //结果== 9

I've seen both terms be used almost interchangeably in various online explanations, and most text books I've consulted are also not entirely clear about the distinction.

Is there perhaps a clear and simple way of explaining the difference that you guys know of?

Type conversion (also sometimes known as type cast)

To use a value of one type in a context that expects another.

Nonconverting type cast (sometimes known as type pun)

A change that does not alter the underlying bits.

Coercion

Process by which a compiler automatically converts a value of one type into a value of another type when that second type is required by the surrounding context.

解决方案

Type Conversion:

The word conversion refers to either implicitly or explicitly changing a value from one data type to another, e.g. a 16-bit integer to a 32-bit integer.

The word coercion is used to denote an implicit conversion.

The word cast typically refers to an explicit type conversion (as opposed to an implicit conversion), regardless of whether this is a re-interpretation of a bit-pattern or a real conversion.

So, coercion is implicit, cast is explicit, and conversion is any of them.


Few examples (from the same source) :

Coercion (implicit):

double  d;
int     i;
if (d > i)      d = i;

Cast (explicit):

double da = 3.3;
double db = 3.3;
double dc = 3.4;
int result = (int)da + (int)db + (int)dc; //result == 9

这篇关于是什么铸造和胁迫之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆