java - 为什么 `++a++` 不能用 C++ 编译但 `(++a)++` 可以?

标签 java c++ lvalue rvalue

<分区>

标题说的是什么。对于 C++,(++a)++ 会编译。不过,奇怪的是,++(a++) 不会:

int main() {
    int a = 0;
    ++a++; // does not compile
    (++a)++; // does compile
    ++(a++); // does not compile
}

但在 Java 中,它并不适用于所有这三个:

public class Test {
    public static void main(String[] args) {
        int a = 0;
        ++a++; // does not compile
        (++a)++; // does not compile
        ++(a++); // does not compile
    }
}

C++ 编译它而不是 Java 有什么原因吗?

最佳答案

所有示例都无法在 Java 中运行,因为后缀和前缀递增操作都返回 而不是变量 我们可以通过转到 JLS 看到这一点关于 Postfix Increment Operator ++ 的部分举个例子,它说:

The result of the postfix increment expression is not a variable, but a value.

Prefix Increment Operator ++ 的 JLS 部分说同样的话。

这就像尝试增加文字值 ( see it live ):

2++ ;
++3 ;

出现以下错误:

required: variable
found:    value

这与我们在您的示例中收到的错误相同。

在 C++ 中,前缀增量返回一个左值,但后缀增量返回一个纯右值,并且 C++ 中的前缀和后缀增量都需要一个左值。所以你的第一个和第三个 C++ 示例:

++a++;
++(a++)

失败是因为您正试图将前缀增量应用于纯右值。而第二个 C++ 示例:

(++a)++;

没问题,因为前缀增量返回一个左值。

供引用draft C++ standard5.2 后缀表达式 中说:

The value of a postfix ++ expression is the value of its operand [...] The operand shall be a modifiable lvalue

和:

The result is a prvalue

5.3 一元表达式 说:

The operand of prefix ++ is modified [...] The operand shall be a modifiable lvalue

和:

The result is the updated operand; it is an lvalue

关于java - 为什么 `++a++` 不能用 C++ 编译但 `(++a)++` 可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27021465/

相关文章:

java - Tomcat JNDI 返回 null 而不是 bean

Java在源码中设置Kafka保留时间

java - 是否可以将随机访问文件中的特定字节设置回空?

c++ - Negamax 实现似乎不适用于井字游戏

Javascript 三元运算符左值

c++ - 在 RValue 对象上调用 LValue ref 限定成员函数

java - 使用 java Kafka 客户端的测试中出现间歇性异常

指向成员函数的 C++ 函数指针 - 它接收哪个地址?

c++ - 是否可以保存当前视口(viewport),然后在下一个绘制周期中在 OpenGL 和 C++ 中重新绘制保存的视口(viewport)?

c++ - 关于左值到右值的转换