为什么i + 1会增加,而i ++则没有

elp*_*elp -4 java

让我们说我得到了这段代码:

public class Incrementor {

    private int i;

    public int getInt(){
        return i;
    }

    private void incrementA(){
        i = i+1;
    }

    private void incrementB(){
        i = i++;
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 当我在调用incrementA()之前调用getInt()该值时将为1.
  • 当我在调用incrementB()之前调用getInt()该值时将为0.

Som*_*ude 5

分配

i = i++;
Run Code Online (Sandbox Code Playgroud)

基本上相当于

// These two lines corresponds to i++
int temporary_variable = i;
i = i + 1;

// This line is your assignment back to i
i = temporary_variable;
Run Code Online (Sandbox Code Playgroud)

后缀++运算符在递增之前返回值.

如果您只想增加变量,则不需要赋值,因为它内置于++操作本身:

private void incrementB(){
    i++;  // Increment i by one
}
Run Code Online (Sandbox Code Playgroud)