且构网

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

Java 参考和 C++ 参考有什么区别

更新时间:2023-11-10 13:28:52

Java 引用更接近 C++ 指针,而不是 C++ 引用.在 Java 中,您可以通过引用执行以下操作:

Java references are much closer to C++ pointers rather than C++ references. In Java, you can do the following with a reference:

  • 更改它引用的对象
  • 检查两个引用是否相等或不相等
  • 向引用的对象发送消息.

在 C++ 中,指针具有这些相同的属性.因此,您在 C++ 中寻找的代码类似于

In C++, pointers have these same properties. As a result, the code you're looking for in C++ is something like

float* f = new float;

这是完全合法的.为了更好的比较,这段 Java 代码:

Which is perfectly legal. For a better comparison, this Java code:

String myString = new String("This is a string!"); // Normally I wouldn't allocate a string here, but just for the parallel structure we will.
System.out.println(myString.length());

/* Reassign myString to point to a different string object. */
myString = new String("Here's another string!");
System.out.println(myString.length());

将映射到此 C++ 代码:

would map to this C++ code:

std::string* myString = new std::string("This is a string");
std::cout << myString->length() << std::endl;

delete myString; // No GC in C++!

/* Reassign myString to point to a different string object. */
myString = new std::string("Here's another string!");
std::cout << myString->length() << std::endl;

delete myString; // No GC in C++!

希望这有帮助!