简体   繁体   English

Java的演员和C ++的演员阵容

[英]Java's casting and C++'s casting

I come from C++ and just know some Java, but there is one thing that I don't fully understand about java is the casting. 我来自C ++,只知道一些Java,但有一点我不完全了解java是铸造。 In c++, we have Regular cast vs. static_cast vs. dynamic_cast . 在c ++中,我们有Regular cast vs. static_cast与dynamic_cast In java, we have casting between primitive types and object types (known as boxing and unboxing), casting between primitive types, casting using Class function, and sometimes we perform unchecked casting. 在java中,我们在基本类型和对象类型(称为装箱和拆箱)之间进行转换,在基本类型之间进行转换,使用Class函数进行转换,有时我们执行未经检查的转换。 Is there a direct mapping from Java's casting system to C++'s casting system? 是否有从Java的演员系统到C ++的演员系统的直接映射? are they equivalent? 他们相同吗? or is there something that is unique in one side? 或者在一边有什么独特之处吗?

If you know C++, the Java object model can be explained fairly easily. 如果您了解C ++,则可以非常轻松地解释Java对象模型。 Java variables of class type are references to dynamically created objects of the corresponding type. 类类型的Java变量是对相应类型的动态创建对象的引用 An initialized Java variable T x = new T(); 初始化的Java变量T x = new T(); corresponds closely to a C++ pointer: T * px = new T; 与C ++指针紧密对应: T * px = new T;

In Java, all class types inherit from the polymorphic type Object , and thus all pointers can be used for RTTI: All casts of Java class-type variables are what dynamic_cast is in C++. 在Java中,所有类类型都继承自多态类型Object ,因此所有指针都可用于RTTI:Java类类型变量的所有类型转换都是C ++中的dynamic_cast So Java's (S) x corresponds to dynamic_cast<S *>(px) in C++, with the same failure mode that a null result indicates that the dynamic types aren't related. 因此,Java的(S) x对应于C ++中的dynamic_cast<S *>(px) ,具有相同的失败模式,即null结果表明动态类型不相关。

All the other C++ pointer casts are unsafe and have no equivalent in Java. 所有其他C ++指针强制转换都是不安全的,并且在Java中没有等价物。 I don't know if Java has scalar conversions like integer-to-floating point; 我不知道Java是否有像整数到浮点的标量转换; if so, then those would correspond closely to the C++ conversions. 如果是这样,那么那些将与C ++转换密切对应。

Boxing and primitive types are a rather separate and unrelated issue. 拳击和原始类型是一个相当独立和无关的问题。 If you wanted something like that in C++ you'd have some kind of template <typename T> struct Box with a conversion-to- T operator. 如果你想在C ++中使用类似的东西,你会有一些带有转换为T运算符的template <typename T> struct Box

In short: 简而言之:

Think about casts from built-in types as static_cast's and 将内置类型的强制转换视为static_cast和

think about casts between objects as dynamic_cast's in C++. 考虑在C ++中将对象之间的强制转换视为dynamic_cast。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM