C ++或Java中的类型转换和类型转换之间有什么区别?

C ++或Java中的类型转换和类型转换之间有什么区别?

问题描述:

在C ++或Java中类型转换和类型转换之间有什么区别?

What is the difference between typecasting and typeconversion in C++ or Java ?

类型 casting 将变量引用的值(内存块)视为与声明该变量的类型不同的类型。

Type casting is treating a value (block of memory) referenced by a variable as being of a different type than the type the variable is declared as.

类型 转换 实际上是在执行该值的转换。

Type conversion is actually performing a conversion of that value.

在许多语言中,有些强制转换(通常是数字强制转换)确实会导致转换(这会因语言而有所不同),但大多数情况下只是将X作为Y处理。

In many languages, some casts (usually numeric ones) do result in conversions (this will vary quite a bit by language), but mostly it's just "treat this X as a Y".

与人类语言的大多数方面一样,不幸的是,这些术语在不同社区中的使用略有不同,主要是沿语言行列。例如,请参阅下面James关于C ++的评论。 cast一词的含义比上述定义要广泛得多,在C或Java模式中更是如此。只是为了使事情变得有趣,Java语言规范实际上涉及到各种种类强制转换,包括 广播转换

Like most aspects of human language, unfortunately the terms are used slightly differently in different communities, mostly along language lines. For instance, see James' comment below about C++ — the word "cast" there has a much broader meaning than the above definition, which is more in the C or Java mold. And just to make things fun, the Java Language Spec actually gets into various kinds of casts, including casting conversions. But the above is a good rule of thumb.

但是,举一个简单的例子:

But to take a simple case:

在Java中,在使用泛型之前,在处理地图时通常要进行 lot 类型转换:

In Java, prior to generics it wasn't unusual to have to do a lot of typecasting when dealing with maps:

Map m = new HashMap();
m.put("one", "uno");

// This would give a compiler error, because although we know
// we'll get a String back, all the compiler knows is that it's
// an Object
String italian = m.get("one");

// This works, we're telling the compiler "trust me, it's a String"
String italian = (String)m.get("one");

幸运的是,添加了泛型解决了这一问题,因为以这种方式进行转换通常是一个脆弱的过程,存在维护问题。

Fortunately, the addition of generics addressed this, as casting in this way tends to be a fragile process with maintenance issues.

如果您有数字字符串,则可以转换

In contrast, you'd convert if you had a String of digits:

String s = "1234";

...并且需要知道这些数字用十进制表示的数字:

...and needed to know what number those digits represented in decimal:

// Wrong (cast)
int n = (int)s;

// Right (conversion)
int n = Integer.parseInt(s, 10);