Java引用和C ++引用之间的区别是什么 [英] What's the difference between a Java reference and C++ reference

查看:306
本文介绍了Java引用和C ++引用之间的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在想(在阅读这个Java pdf)...



我知道这可能看起来很蠢,但为什么我不能这样做在c + 。

  float& f = new float; 

这不是说f的引用是新float的地址?



在Java中,我看到了这样的东西。

  String s = new String )

String s 参考。

Java中的'reference'一词是否与C ++中的含义相同?

解决方案

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




  • 更改其引用的对象

  • 检查两个引用是否相等或不相等

  • 向引用对象发送消息。



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

  float * f = new float; 

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

  String myString = new String(This is a string! //通常我不会在这里分配一个字符串,但只是为了并行结构。 
System.out.println(myString.length());

/ *重新指定myString以指向不同的字符串对象。 * /
myString = new String(这是另一个字符串!
System.out.println(myString.length());

会映射到此C ++代码:

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

delete myString; // C ++中没有GC!

/ *重新指定myString以指向不同的字符串对象。 * /
myString = new std :: string(这是另一个字符串!
std :: cout<< myString-> length()<< std :: endl;

delete myString; // C ++中没有GC!

希望这有助于!


So I've been thinking (while reading this Java pdf)...

I know this may seem silly but why can't I do this in c++.

float &f = new float;

Isn't this saying the reference of f is the address of new float?

In Java, I see something like this

String s = new String("something")

String s is called a string reference.

Does the word 'reference' in Java have the same meaning as in C++?

解决方案

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

  • Change which object it refers to
  • Check whether two references are equal or unequal
  • Send messages to the referenced object.

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;

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());

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++!

Hope this helps!

这篇关于Java引用和C ++引用之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆