简体   繁体   English

将变量分配给前增量变量和后增量变量?

[英]assigning a variable to pre-increment variable and post increment variable?

What's the difference between the following two assignments? 以下两个作业有什么区别?

#include<iostream>

using namespace std;
int main(){
    int a=10,i=0;
    ++i = a //COMPILES WITHOUT ERROR
    i++ = a //GIVES AN ERROR LVALUE NEEDED
}

Why does the second assignment produce error? 为什么第二个作业会产生错误?

++i returns the new value of i after the incrementation. ++i返回的新值i的递增后。 That value is an lvalue , called i in this case. 该值是一个左值 ,在这种情况下称为i Modifying i is certainly allowed. 修改i当然是允许的。

But i++ returns the old value of i before the incrementation. i++回报的原值i的递增前。 That value is an rvalue , ie an unnamed temporary value. 该值是一个rvalue ,即一个未命名的临时值。 Modifying an rvalue is not allowed in C++. C ++中不允许修改右值。

Pre-increment operation returns its argument ( i ) already incremented by one. 预递增操作将返回其参数( i )已递增1。 The returned thing is a variable and you can assign to it. 返回的东西是一个变量 ,您可以分配给它。

Post-increment returns an old value of i - an rvalue , that cannot be assigned to. 后增量返回无法分配的旧值i - rvalue

See this question for implementation of operator++ in C++. 有关在C ++中实现operator++ ,请参见此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM