让我们说我得到了这段代码:
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.分配
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)