使用 C++ 时需要左值作为赋值错误的左操作数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33375136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:15:50  来源:igfitidea点击:

lvalue required as left operand of assignment error when using C++

c++pointersrequiredlvalue

提问by Kishan Kumar

int main()
{

   int x[3]={4,5,6};
   int *p=x;
   p +1=p;/*compiler shows error saying 
            lvalue required as left 
             operand of assignment*/
   cout<<p 1;
   getch();
}

回答by R Sahu

When you have an assignment operator in a statement, the LHS of the operator must be something the language calls an lvalue. If the LHS of the operator does not evaluate to an lvalue, the value from the RHS cannot be assigned to the LHS.

当语句中有赋值运算符时,运算符的 LHS 必须是语言称为lvalue 的东西。如果运算符的 LHS 不计算为lvalue,则无法将 RHS 中的值分配给 LHS。

You cannot use:

您不能使用:

10 = 20;

since 10does not evaluate to an lvalue.

因为10不计算为lvalue

You can use:

您可以使用:

int i;
i = 20;

since idoes evaluate to an lvalue.

因为i确实评估为lvalue

You cannot use:

您不能使用:

int i;
i + 1 = 20;

since i + 1does not evaluate to an lvalue.

因为i + 1不计算为lvalue

In your case, p + 1does not evaluate to an lavalue. Hence, you cannot use

在您的情况下,p + 1不会评估为lavalue。因此,您不能使用

p + 1 = p;

回答by jh314

To assign, you should use p=p+1;instead of p+1=p;

要分配,您应该使用p=p+1;而不是p+1=p;

int main()
{

   int x[3]={4,5,6};
   int *p=x;
   p=p+1; /*You just needed to switch the terms around*/
   cout<<p<<endl;
   getch();
}

回答by Rimon

if you use an assignment operator but use it in wrong way or in wrong place, then you'll get this types of errors!

如果您使用赋值运算符但以错误的方式或在错误的位置使用它,那么您将遇到此类错误!

suppose if you type:
p+1=p; you will get the error!!

假设你输入:
p+1=p; 你会得到错误!

you will get the same error for this:
if(ch>='a' && ch='z')
as you see can see that I i tried to assign in if() statement!!!
how silly I am!!! right??
ha ha
actually i forgot to give less then(<) sign
if(ch>='a' && ch<='z')
and got the error!!

你会得到同样的错误:
if(ch>='a' && ch='z')
如你所见,我试图在 if() 语句中赋值!!!
我多傻啊!!!对??
哈哈
实际上我忘了给 less then(<) 符号
if(ch>='a' && ch<='z')
并得到错误!

回答by ameyCU

It is just a typo(I guess)-

这只是一个错字(我猜)-

p+=1;

instead of p +1=p;is required .

而不是p +1=p;是必需的。

As name suggest lvalueexpression should be left-hand operand of the assignment operator.

顾名思义,lvalue表达式应该是赋值运算符的左侧操作数。

回答by dbush

Put simply, an lvalue is something that can appear on the left-hand side of an assignment, typically a variable or array element.

简而言之,左值是可以出现在赋值左侧的东西,通常是变量或数组元素。

So if you define int *p, then pis an lvalue. p+1, which is a valid expression, is not an lvalue.

所以如果你定义了int *p,那么p是一个左值。 p+1,这是一个有效的表达式,不是左值。

If you're trying to add 1 to p, the correct syntax is:

如果您尝试将 1 添加到p,则正确的语法是:

p = p + 1;