【问题标题】:C static variable behaviour in javajava中的C静态变量行为
【发布时间】:2014-02-23 16:43:17
【问题描述】:
void func()
{
    static int a=10;
    println("\na is ::%d",a);
     a++;
}
int main(){
    int i=1;
    while(i<6){
        func();
    }
}

这将使输出为

10
11 
12
13
14

所以这是c中静态变量的默认行为。我想知道java中是否有针对相同行为的内置技术?

【问题讨论】:

  • 您是否尝试过将其更改为 Java 程序?据我所知:是的,它的工作原理是一样的。 static 变量是类级别,而不是实例级别。

标签: java c static


【解决方案1】:

你可以这样...

class A
{
   static int a=0;
   static void func()
   {
        System.out.print("\na is ::%d",a);
        a++;
   }
   public static void main(String args[])
   {
        int i=1;
        while(i<6){
           func();
           i++;
        }
    }
}

【讨论】:

  • 应该是static int a=10; static void func() { System.out.printf("\na is ::%d",a); a++; }
  • 当然可以。但似乎没有内置的方法。
  • @Neuron 上面的 sn-p 给出错误为func() non static ,cannot be referenced from a static context
  • @Intriguing 是的,对不起,因为我从非静态方法调用静态变量,这是不可能的。
【解决方案2】:

如果你有一个类构造,它在实例化时增加一个静态变量,那么是的,行为将是相同的。

这是一个sn-p。

public class StaticExample {
    private static int val = 0;

    public StaticExample() {
        val++;
    }

    public static int getVal() {
        return val;
    }
}

使用以下迭代代码:

for(int i = 0; i < 10; i++) {
    new StaticExample();
    System.out.println(StaticExample.getVal());
}

...我得到这个结果:

1
2
3
4
5
6
7
8
9
10

【讨论】:

    猜你喜欢
    • 2011-04-07
    • 2015-02-19
    • 2010-11-14
    • 2012-09-12
    • 2016-02-07
    • 1970-01-01
    • 2013-04-05
    • 2011-04-11
    相关资源
    最近更新 更多