这可能看起来像一个愚蠢的问题,但这个函数实际上会影响变量bool
(我将如何使用它有更大的背景,但这基本上是我不确定的)?(我具体询问java)
void truifier (boolean bool) {
if (bool == false) {
bool = true;
}
}
Run Code Online (Sandbox Code Playgroud)
poh*_*ohl 16
考虑一个稍微不同的例子:
public class Test {
public static void main(String[] args) {
boolean in = false;
truifier(in);
System.out.println("in is " + in);
}
public static void truifier (boolean bool) {
if (bool == false) {
bool = true;
}
System.out.println("bool is " + bool);
}
}
Run Code Online (Sandbox Code Playgroud)
运行此程序的输出将是:
bool is true
in is false
Run Code Online (Sandbox Code Playgroud)
该bool
变量将改为真实的,但只要truifier
方法返回,这样的说法变消失(这是当他们说,它"超出范围"是什么意思的人).但是,in
传递给truifier
方法的变量保持不变.
但是,如果您没有使用布尔值,而是使用对象,则参数可以修改对象.正如另一个响应所指出的,当作为参数传递时,将在本地为您的truifier函数创建一个布尔值,但是一个对象将按位置引用.因此,根据您使用的参数类型,您可以得到两个非常不同的结果!
class Foo {
boolean is = false;
}
class Test
{
static void trufier(Foo b)
{
b.is = true;
}
public static void main (String[] args)
{
// your code goes here
Foo bar = new Foo();
trufier(bar);
System.out.println(bar.is);
}
}
Run Code Online (Sandbox Code Playgroud)
//这个代码输出正确