c++中可以通过参数传递类的实例,进而访问非静态变量。但是有一本《深入浅出java2面向对象程序设计》说,静态函数无法访问非静态变量,说的对吗。
我编了个验证程序,试了一下输出888,是书上说的有问题吗?望高人指点。
public class Example {
public static void main(String[] str1){
Example e=new Example();
f1(e,888);
}
public static void f1(Example a,int b)
{
a.num=b;
System.out.print(a.num);
}
int num;
}
我编了个验证程序,试了一下输出888,是书上说的有问题吗?望高人指点。
public class Example {
public static void main(String[] str1){
Example e=new Example();
f1(e,888);
}
public static void f1(Example a,int b)
{
a.num=b;
System.out.print(a.num);
}
int num;
}
比如你在f1里直接访问num是不可以的
静态方法不能直接访问非静态成员。当调用静态方法时,不存在该方法能够操作的特定对象,所以也没有this引用。我们可以将一个显示的对象引用作为引元传给静态方法来达到访问非静态成员的目的。
2 你传过去一个对象,已经实例化了,就能访问了。OVER 结贴,给分!
是说这种情况class Test{
int i;
static void setTest(){
i = 1;//这样编译出错
}
}