我只是阅读了以下有关按引用传递和按值传递意味着什么的文章:http : //qntm.org/call
因此,请确保我正确理解...这是否意味着在函数中按值调用不会更改原始输入,而不会更改该输入的本地副本?但是,由于在Java和Python中,值实际上是对值的引用,这是否意味着在函数中按值调用会改变原始输入?
这取决于您输入的确切含义,尤其取决于您是指一个变量,该变量在调用站点上作为参数出现,例如x
:
Object x = ...;
someMethod( x );
或者您正在谈论被调用函数将看到的实际对象,例如,实际的Object实例位于:
someMethod( new Object() );
变量的值(即它们引用的对象)不会改变,但是您仍然可以对所获得的对象进行处理。例如,
void appendX( StringBuilder sb ) {
sb.append('x');
}
void foo() {
StringBuilder builder = ...
appendX( builder );
builder.toString(); // will contain 'x' because you worked with the object that
// is the value of the variable `builder`. When appendX was
// was invoked, the value of its variable `sb` was the same
// object that is the value of foo's `builder`. Without
// changing what value the variable `builder` refers to, we
// did "change" the object (i.e., we appended 'x').
}
但是,更新方法中的引用不会更改方法之外的任何引用。从方法内部,不能通过将方法赋值给方法的一个参数来更改方法外部引用的对象。例如:
void setNull( StringBuilder sb ) {
sb = null;
}
void foo() {
StringBuilder builder = ...
appendX( builder );
builder == null; // false, because the value of the variable `builder` is still the
// same object that it was before. Setting variable `sb` in setNull
// to null doesn't affect the variable `builder`. The variables are
// just a name so that you can refer to an value. The only way to
// what value a variable refers to is with an assignment.
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句