在c ++或java中typecasting和typeconversion之间有什么区别? [英] what is the difference between typecasting and typeconversion in c++ or java?

查看:626
本文介绍了在c ++或java中typecasting和typeconversion之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++或java中的typecasting和typeconversion之间有什么区别?

what is the difference between typecasting and typeconversion in c++ or java ?

推荐答案

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

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.

在许多语言中, em> casts(通常是数字)会产生转换(这种情况会因语言而有所不同),但大多数情况下只是将此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.

在Java中,

在处理地图之前,必须进行很多类型转换:

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.

相反, > convert 如果您有一个数字字符串:

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);

这篇关于在c ++或java中typecasting和typeconversion之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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