gpt4 book ai didi

java - 比较 Java 的按值传递与 C++ 的按值传递或引用

转载 作者:太空宇宙 更新时间:2023-11-04 14:45:16 26 4
gpt4 key购买 nike

Java 对对象和原始类型都使用按值传递。因为Java传递的是引用的值,我们可以改变target的值,但不能改变地址。

这与 C++ 相比如何?

最佳答案

区别在于您是否可以影响调用函数中的变量。

让我们暂时把对象放在一边。在纯粹按值传递的 Java 中,您不能更改传递给被调用函数的变量的调用函数值。示例:

void foo() {
int a = 42;
bar(a);
System.out.println("foo says: " + a);
}
void bar(int a) {
a = 67;
System.out.println("bar says: " + a);
}

如果调用 foo,您将看到:

bar says: 67foo says: 42

bar could not change foo's a.

That's true in C++ if you pass by value. However, if you pass by reference, you're passing a reference to the calling code's variable. And that means the called code can change it:

void foo() {
int a = 42;
bar(a);
cout << "foo says: " << a;
}
void bar(int& a) {
a = 67;
cout << "bar says: " << a;
}

请注意,bar 被定义为接收一个reference (int& a)。如果你调用 bar,你会看到:

bar says: 67foo says: 67

bar was able to change the value of a within foo.

Okay, so let's deal with object references: First off, note that the word "reference" is being used for two completely different things: A reference to the variable in the calling function (that's the pass-by-reference thing), and a reference to an object. When you pass an object reference into a method in Java, the reference is passed by value, just like everything else is.

void foo() {
List list = new ArrayList();
List ref2 = list; // (Let's remember that object reference for later...)
bar(list);
System.out.println("foo says: " + list.size());
System.out.println("foo says: Same list? " + (ref2 == list));
}
void bar(List list) {
// `bar` can modify the state of the object the reference points to
list.add(new Object());
System.out.println("bar says (after add): " + list.size());

// ...but cannot change `foo`'s copy of `list`
list = new ArrayList();
System.out.println("bar says (after new): " + list.size());
}

所以你看到了:

bar says (after add): 1bar says (after new): 0foo says: 1foo says: same list? true

bar 可以改变(按值)传入其引用的对象的状态,但不能改变foo对那个对象。 foo 没有看到创建的新列表 bar

关于java - 比较 Java 的按值传递与 C++ 的按值传递或引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13515227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com