且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“一般”和“一般”之间的区别是什么,类型在C ++和Java?

更新时间:2023-01-10 22:41:23

在C ++中,您不必为通用类型指定类或接口。这就是为什么你可以创建真正的泛型函数和类,带有更宽松的打字的警告。

There is a big difference between them. In C++ you don't have to specify a class or an interface for the generic type. That's why you can create truly generic functions and classes, with the caveat of a looser typing.

template <typename T> T sum(T a, T b) { return a + b; }

上面的方法添加了两个相同类型的对象,可以用于任何类型T

The method above adds two objects of the same type, and can be used for any type T that has the "+" operator available.

在Java中,如果你想对传递的对象调用方法,你必须指定一个类型:

In Java you have to specify a type if you want to call methods on the objects passed, something like:

<T extends Something> T sum(T a, T b) { return a.add ( b ); }

在C ++中泛型函数/类只能在头文件中定义,因为编译器生成不同的函数不同的类型(它被调用)。所以编译慢。在Java中,编译没有重大的代价,但是Java使用了一种名为擦除的技术,其中通用类型在运行时被擦除,因此在运行时Java正在调用...

In C++ generic functions/classes can only be defined in headers, since the compiler generates different functions for different types (that it's invoked with). So the compilation is slower. In Java the compilation doesn't have a major penalty, but Java uses a technique called "erasure" where the generic type is erased at runtime, so at runtime Java is actually calling ...

Something sum(Something a, Something b) { return a.add ( b ); }

因此,Java中的泛型编程并不真正有用,它只是一个小的语法糖新的foreach构造。

So generic programming in Java is not really useful, it's only a little syntactic sugar to help with the new foreach construct.

编辑:有用性的意见是由一个年轻的自我写的。当然,Java的泛型有助于类型安全。

the opinion above on usefulness was written by a younger self. Java's generics help with type-safety of course.