C++ 错误:只读变量的赋值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20598420/
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-27 23:14:41  来源:igfitidea点击:

C++ error: assignment of read-only variable

c++

提问by mxmolins

I have some C++ code that returns this error:

我有一些返回此错误的 C++ 代码:

error: assignment of read-only variable ‘parking'

The code:

编码:

char const * const parking= "false";

if (phidgets.value(PHIDGET3V_1) > 1000) {
    parking = "true";
} 
else{
    parking = "false";
}

What does this error mean and how do I fix it?

这个错误是什么意思,我该如何解决?

回答by Gabriel

parkingis set to be const(char const * const parking = "false") so it cannot be modified.

parking设置为const( char const * const parking = "false") 所以它不能被修改。

When you do parking = "true"it raises compile time error.

当你这样做parking = "true"时会引发编译时错误。

How to reproduce the problem very simply to illustrate:

如何复现问题很简单来说明:

#include <iostream>
int main(){
  const int j = 5;
  j = 7;
}

constmeans constant, meaning you are not allowed to change it:

const表示常量,意思是你不能改变它:

error: assignment of read-only variable ‘j'

回答by Vlad from Moscow

You declared parking as constant pointer.

您将停车声明为常量指针。

char const * const parking= "false";

So it will point only to string literal "false"and may not be changed.

所以它只会指向字符串文字"false"并且可能不会改变。

Also this statement

还有这个说法

char const * const message = "Value: "+ parking +" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy";

is invalid. There is no addition operator for pointers.

是无效的。指针没有加法运算符。

回答by shuttle87

In your code you set up the parking variable with a const, this is telling the compiler that it will not be modified later. You then modify parking later by setting it to true or false.

在您的代码中,您使用 a 设置了停车变量const,这告诉编译器以后不会修改它。然后您稍后通过将其设置为 true 或 false 来修改停车。

Using std::stringis far more idiomatic c++ though. So I would do this instead:

不过,使用std::stringC++ 更为惯用。所以我会这样做:

  #include<string>
  std::string parking = "false";

  if (phidgets.value(PHIDGET3V_1) > 1000) {
      parking = "true";
      //leds_on(LEDS_RED);
    } else {
      parking = "false";
      //leds_off(LEDS_RED);
    }
std::string message = "Value: "+ parking +" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy";

std::stringoverloads +to do concatenation so it does what you think it does in the last line. Previously you were adding some pointers and that probably doesn't do what you think it does.

std::string重载+以进行连接,因此它执行您认为在最后一行中执行的操作。以前您添加了一些指针,但这可能与您认为的不一样。