c ++或java中的类型转换和类型转换有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4049580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:56:28  来源:igfitidea点击:

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

javac++casting

提问by Jagan

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

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

采纳答案by T.J. Crowder

Type castingis 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 conversionis actually performing a conversion of that value.

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

In many languages, somecasts (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".

在许多语言中,一些转换(通常是数字转换)确实会导致转换(这会因语言而异),但大多数情况下只是“将此 X 视为 Y”。

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 kindsof casts, including casting conversions. But the above is a good rule of thumb.

与人类语言的大多数方面一样,不幸的是,这些术语在不同社区的使用略有不同,主要是沿语言线。例如,请参阅下面 James 对 C++ 的评论——“cast”一词在那里的含义比上面的定义要广泛得多,它更像是 C 或 Java 模型。为了让事情变得有趣,Java 语言规范实际上涉及各种类型的强制转换,包括强制转换。但以上是一个很好的经验法则。

But to take a simple case:

但举个简单的例子:

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

在 Java 中,在泛型之前,在处理映射时必须进行大量类型转换并不少见:

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 genericsaddressed this, as casting in this way tends to be a fragile process with maintenance issues.

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

In contrast, you'd convertif 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);

回答by joni

Typecasting is just taking a pen and writing "this is now a int" on the variable, conversion is actually convert the content to the desired type so the value keeps having a sense.

类型转换只是拿一支笔在变量上写下“这现在是一个 int”,转换实际上是将内容转换为所需的类型,因此该值始终具有意义。

回答by vitaut

According to the Wikipedia article:

根据维基百科文章

"In the C family of languages, the word cast typically refers to an explicit type conversion (as opposed to an implicit conversion), regardless of whether this is a re-interpretaion of a bit-pattern or a real conversion."

“在 C 语言家族中,cast 这个词通常指的是显式类型转换(而不是隐式转换),无论这是对位模式的重新解释还是真正的转换。”

Here is a C++ example:

这是一个 C++ 示例:

double d = 42.0;
int i = d; // Here you have an implicit conversion from double to int
int j = static_cast<int>(d); // Here you have a cast (explicit conversion).

Here is a Java example (note that in Java unlike C++ you can't implicitly convert from double to int):

这是一个 Java 示例(请注意,在 Java 中,与 C++ 不同的是,您不能从 double 隐式转换为 int):

int i = 42;
double d = i; // Here you have an implicit conversion from int to double
int j = (int)d; // Here you have a cast (explicit conversion).

回答by user225312

Type conversion:

类型转换:

double value = 3; // implicit conversion to double value 3.0
int nValue = 3.14156; // implicit conversion to integer value 3

Casting is a request by the programmer to do an explicit type conversion.

强制转换是程序员进行显式类型转换的请求。

int nValue = 10;
double dvalue = double(nValue); // explicit type casting

回答by Merlyn Morgan-Graham

The terms are often used interchangeably.

这些术语经常互换使用。

Java

爪哇

Type casting and type conversion are the same thing in Java, though if someone says that they are casting, they are usually referring to an explicit conversion.

类型转换和类型转换在 Java 中是一回事,但如果有人说他们在转换,他们通常指的是显式转换。

A cast in Java will be done at runtime, so can potentially fail (throw an exception). Some types of invalid casts can be caught at compile time. When the cast fails, the instance was seated in an objectreference, so the compiler couldn't tell what cast was going to be performed, until it actually ran the code.

Java 中的强制转换将在运行时完成,因此可能会失败(抛出异常)。某些类型的无效转换可以在编译时被捕获。当转换失败时,实例位于object引用中,因此编译器无法判断将要执行的转换,直到它实际运行代码。

C++

C++

Type casting and type conversion are different in C++. There are five types of casts in C++, which all have different behavior: static_cast, dynamic_cast, reinterpret_cast, const_cast, and c-style casts ((int)someVariable).

C++ 中的类型转换和类型转换是不同的。有五种类型的C ++类型转换,它们都具有不同的行为:static_castdynamic_castreinterpret_castconst_cast,和C风格的转换((int)someVariable)。

Some C++ casts perform type conversion (hence why this concept is confusing), calling code and potentially doing runtime checks. Other C++ casts simply fake the type change of the referring variable - no memory will be modified, moved, or copied, so the resulting datatype might not be properly converted. This can give great speed at runtime, and can be a powerful tool for low-level code, but tends to be avoided for high level code.

一些 C++ 强制转换执行类型转换(因此这个概念令人困惑),调用代码并可能进行运行时检查。其他 C++ 转换只是伪造引用变量的类型更改 - 不会修改、移动或复制内存,因此结果数据类型可能无法正确转换。这可以在运行时提供极大的速度,并且可以成为低级代码的强大工具,但往往避免用于高级代码。

Note that the c-style cast syntax (which happens to look exactly like the Java syntax) is one of the casts that will not necessarily call conversion code.

请注意,c 样式的强制转换语法(恰好看起来与 Java 语法完全一样)是不一定调用转换代码的强制转换之一。

Type conversion in C++ often refers to calling a copy constructor or assignment operator, which will copy data over to a new instance of a different class/structure. If a type has conversion operators defined, then the conversion syntax could look like a cast, or simply a straight assignment. The main difference here is that code is called to do the conversion.

C++ 中的类型转换通常是指调用复制构造函数或赋值运算符,这会将数据复制到不同类/结构的新实例。如果类型定义了转换运算符,则转换语法可能看起来像强制转换,或者只是直接赋值。这里的主要区别是调用代码来进行转换。

回答by J?rg W Mittag

Maybe an example can help:

也许一个例子可以帮助:

  • If you cast33to a string, you get "!".
  • If you convert33to a string, you get "33".
  • 如果你33一个字符串,你会得到"!"
  • 如果转换33为字符串,则会得到"33".

[Note: this example makes all sorts of not-necessarily-valid assumptions about the encodings and in-memory representations of numbers and strings, but I hope the mechanism is clear.]

[注意:这个例子对数字和字符串的编码和内存表示做出了各种不必要的假设,但我希望机制是明确的。]

回答by Rajdeep Sarkar

From an object to primitive -> Type conversion

从对象到原始类型 -> 类型转换

String s = "1234";
int i = Integer.parseInt(s);
int j = Integer.valueOf(s);

From an primitive to object -> Type conversion

从原始对象到对象 -> 类型转换

int i = 55;
String s = String.valueOf(i);
String t = Integer.toString(i);

From a primitive to primitive(or object to object) -> Type casting(explicit when narrowing and implicit when widening)

从原始到原始(或对象到对象)-> 类型转换(缩小时显式,扩大时隐式)

//explicit  
double d = 3.14156;
int i = (int)d; 
//implicit
int i = 100;
double d = i;

Note: In case of object type casting, we cannot use child class reference to hold parent object

注意:在对象类型转换的情况下,我们不能使用子类引用来保存父对象

回答by MMKarami

If you concentrate on Java and numeric types, according Javadoc I think the main differences between type casting and type conversion are:

如果您专注于 Java 和数字类型,根据 Javadoc,我认为类型转换和类型转换之间的主要区别是:

  • without information and precision loss (type conversion)
  • precision loss (type conversion)
  • information loss (type casting)
  • 没有信息和精度损失(类型转换)
  • 精度损失(类型转换)
  • 信息丢失(类型转换)

To consider more detail, first(without information and precision loss), conversion can be done without information and precision loss. These conversions include: byte to short, short to int, char to int, int to long, int to double and finally float to double. For example:

要考虑更多细节,首先(没有信息和精度损失),可以在没有信息和精度损失的情况下进行转换。这些转换包括:byte 到 short、short 到 int、char 到 int、int 到 long、int 到 double,最后是 float 到 double。例如:

byte b = 2;
System.out.println(b); 
short s = b; // without information and precision loss (type conversion)
System.out.println(s);

result:

结果:

    2
    2

Secondly(precision loss), conversion is performed with precision loss, it means that the result value has the right magnitude however with precision loss. These conversions include: int to float, long to float and long to double. For example:

其次(精度损失),转换是在精度损失的情况下进行的,这意味着结果值具有正确的大小但是精度损失。这些转换包括:int 到 float、long 到 float 和 long 到 double。例如:

long l = 1234567891;
System.out.println(l); 
double d = l; // precision loss (type conversion)
System.out.println(d);

result:

结果:

    1234567891
    1.234567891E9

Thirdly (information loss), conversion is done via information loss, it means that you are casting the values, so it has its own syntax. These conversions include: double to long, double to int and so forth. For example:

第三(信息丢失),转换是通过信息丢失完成的,这意味着您正在转换值,因此它有自己的语法。这些转换包括:double 到 long、double 到 int 等等。例如:

double d = 1.2;
System.out.println(d); 
long l = (long) d; // information loss
System.out.println(l);

result (fractional part is omitted):

结果(小数部分省略):

    1.2
    1