简体   繁体   English

将增量运算符应用于常量变量时​​,为什么会出现编译器错误

[英]Why do I get a compiler error, when applying the increment operator to a constant variable

If I declare a constant variable 如果我声明一个常量变量

int const n=100; cout<<n+1<<endl;

The console shows the value as 101 控制台将值显示为101

but when I write a code like this: 但是当我写这样的代码时:

int const n=100;
n++;
cout<<n<<endl;

There is a compile time error : 编译时错误

 main.cpp: In function 'int main()': main.cpp:6:5: error: increment of read-only variable 'n' 

Is the second case different from the first case? 第二种情况与第一种情况不同吗?

Is the second case different from the first case? 第二种情况与第一种情况不同吗?

Yes they are fundamentally different. 是的,它们根本不同。

int const n=100; 
n++;

The increment operator obviously cannot applied for a const (ant) variable, because the const keyword prevents it to be changed after the initial definition. 增量运算符显然不能应用const (ant)变量,因为const关键字阻止在初始定义之后更改它。 That's why the compiler error is issued. 这就是发出编译器错误的原因。

In the other case, the variable itself isn't changed, but another temporary value is created when it's passed to the operator<<() of std::cout . 在另一种情况下,变量本身不会更改,但是当它传递给std::coutoperator<<()时会创建另一个临时值。

In the first case the compiler is asked to compute the output of adding a constant to an integer. 在第一种情况下,要求编译器计算向整数添加常量的输出。 This causes no error. 这不会导致错误。

In the second case, the compiler is asked to change the value of a constant. 在第二种情况下,要求编译器更改常量的值。 This is illegal and results in a compiler error. 这是非法的,会导致编译错误。

暂无
暂无

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

相关问题 为什么我的编译器在我重载增量运算符时会出错 - why my compiler give error when i overload increment operator 为什么在使用重载赋值运算符时会出错,但我没有使用编译器提供的赋值运算符? - Why do I get errors when I use the overloaded assignment operator, but I don't get using the compiler-supplied one? 为什么我收到“ operator ^”不匹配的错误 - Why do i get an error no match for 'operator^' 为什么在这种情况下覆盖 stream 插入运算符时会出现“未找到运算符”错误? - Why do I get a “no operator found” error when overriding the stream insertion operator in this situation? 当我的代码在 function scope 之外时,为什么会出现编译器错误“未命名类型”? - Why do I get the compiler error “does not name a type” when my code is outside of a function scope? 为什么在 Clang 中出现此错误? “如果条件不是常量表达式,则为 constexpr” - Why do I get this error in Clang? "constexpr if condition is not a constant expression" 为什么会出现“常数太大”错误? - Why do I get a “constant too large” error? 当我想修改指向常量整数的指针时,为什么我的编译器没有显示错误? - Why does not my compiler show an error when I want to modify a pointer to a constant integer? 为什么我在 + 运算符重载函数返回的对象上重载 &lt;&lt; 时会出错 - Why do I get an error when I overload the << on the object returned by the + operator overloaded function 分配给引用时,为什么会出现此错误(C2582:&#39;operator =&#39;函数在&#39;B&#39;中不可用)? - Why do I get this error (C2582: 'operator =' function is unavailable in 'B') when assigning to a reference?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM