Java 参考和 C++ 参考有什么区别 [英] What's the difference between a Java reference and C++ reference
问题描述
所以我一直在想(在阅读这个 Java pdf 时)...
So I've been thinking (while reading this Java pdf)...
我知道这可能看起来很傻,但为什么我不能在 C++ 中做到这一点.
I know this may seem silly but why can't I do this in c++.
float &f = new float;
这不是说f的引用是new float的地址吗?
Isn't this saying the reference of f is the address of new float?
在 Java 中,我看到类似这样的东西
In Java, I see something like this
String s = new String("something")
String s
称为字符串引用.
Java 中的引用"一词与 C++ 中的含义相同吗?
Does the word 'reference' in Java have the same meaning as in C++?
推荐答案
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++!
希望这有帮助!
这篇关于Java 参考和 C++ 参考有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!