[英]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::cout
的operator<<()
时会创建另一个临时值。
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.