强制转换和强制转换有什么区别? [英] What is the difference between casting and coercing?

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

问题描述

我在各种在线解释中看到这两个术语几乎可以互换使用,而且我查阅过的大多数教科书也没有完全清楚区别.

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?

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

在需要另一种类型的上下文中使用一种类型的值.

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

非转换类型转换(有时称为类型双关)

不会改变底层位的更改.

A change that does not alter the underlying bits.

强制

当周围上下文需要第二种类型时,编译器自动将一种类型的值转换为另一种类型的值的过程.

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.

推荐答案

类型转换:

转换一词是指隐式或显式地将值从一种数据类型更改为另一种数据类型,例如16 位整数到 32 位整数.

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.

cast 一词通常指的是显式类型转换(与隐式转换相对),无论这是对位模式的重新解释还是真正的转换.>

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.

几个例子(来自相同来源):

强制(隐式):

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

演员表(明确):

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天全站免登陆