問題描述
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.
類型 conversion 實際上是在執行該值的轉換.
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.
但舉個簡單的例子:
在 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");
幸運的是,添加 generics 解決了這個問題,因為以這種方式進行投射往往是一種存在維護問題的脆弱流程.
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);
這篇關于C++ 或 Java 中的類型轉換和類型轉換有什么區別?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!