gpt4 book ai didi

java - Java 中的自增运算符可以使用什么类型的操作数?

转载 作者:行者123 更新时间:2023-12-02 09:32:22 25 4
gpt4 key购买 nike

我不知道如果在 Java 中的表达式上应用增量运算符会发生什么。

int ai[] = new ai[10];
ai[0]++;

// ***

class Car {
public int yearMade = 0;
}

class Person {
public Car myCar = new Car();
}

Person p = new Person();
p.myCar.yearMade++;

您可以按照第一个示例所示的方式递增数组的元素吗?

您能否按照我在第二个示例中所示的方式增加类中的字段(我确实了解封装和 getter/setter,我的问题是面向语法语义的)?

我记得 C/C++ 的时代。例如,p -> x++ 曾经存在问题。使用增量或减量时,有时需要将复杂表达式括在括号中。

感谢您的任何提示。

最佳答案

您的两个问题的答案都是“是的,您可以”。 p.myCar.yearMadeai[0] 都是变量 (an instance variable and a local variable, respectively) ,并且,因此可以用作这四个运算符中任何一个的操作数。

4.12. Variables

A variable is a storage location and has an associated type, sometimes called its compile-time type, that is either a primitive type (§4.2) or a reference type (§4.3).

A variable's value is changed by an assignment (§15.26) or by a prefix or postfix ++ (increment) or -- (decrement) operator (§15.14.2, §15.14.3, §15.15.1, §15.15.2).

...

15.14.2. Postfix Increment Operator ++

At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.

关于java - Java 中的自增运算符可以使用什么类型的操作数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57856476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com