Java 与 C++ “引用”的区别

Java中的引用行为更类似于C++中的指针。以下代码作为C++中引用行为与Java引用行为的对比。

C++

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;
class Hello {
public:
string key;
Hello(){
key = "Hello";
};
Hello(string str):key(str){

}
};

int main() {
Hello hello;
Hello & helloRef = hello;
Hello hello1("hello1");
hello = hello1;
cout << "hello.key : \t" << hello.key << endl;
cout << "helloRef.key : \t" << helloRef.key << endl;
Hello hello2("hello2");
helloRef = hello2;
cout << "hello.key : \t" << hello.key << endl;
cout << "helloRef.key : \t" << helloRef.key << endl;
return 0;
}

output

1
2
3
4
hello.key : 	hello1
helloRef.key : hello1
hello.key : hello2
helloRef.key : hello2

Java

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main.java;

public class TestRef {
private static class Hello{
String key;
Hello(){
key = "hello";
}
Hello(String str){
key = str;
}
}
public static void main(String[] args){
Hello hello = new Hello();
Hello helloRef = hello;
Hello hello1 = new Hello("hello1");
hello = hello1;
System.out.println("hello.key : \t" + hello.key);
System.out.println("helloRef.key : \t" + helloRef.key);
Hello hello2 = new Hello("hello2");
helloRef = hello2;
System.out.println("hello.key : \t" + hello.key);
System.out.println("helloRef.key : \t" + helloRef.key);
}
}

output

1
2
3
4
hello.key : 	hello1
helloRef.key : hello
hello.key : hello1
helloRef.key : hello2