[英]Why do I get a compiler error, when applying the increment operator to a constant variable
如果我声明一个常量变量
int const n=100; cout<<n+1<<endl;
控制台将值显示为101
但是当我写这样的代码时:
int const n=100;
n++;
cout<<n<<endl;
有编译时错误 :
main.cpp: In function 'int main()': main.cpp:6:5: error: increment of read-only variable 'n'
第二种情况与第一种情况不同吗?
第二种情况与第一种情况不同吗?
是的,它们根本不同。
int const n=100;
n++;
增量运算符显然不能应用const
(ant)变量,因为const
关键字阻止在初始定义之后更改它。 这就是发出编译器错误的原因。
在另一种情况下,变量本身不会更改,但是当它传递给std::cout
的operator<<()
时会创建另一个临时值。
在第一种情况下,要求编译器计算向整数添加常量的输出。 这不会导致错误。
在第二种情况下,要求编译器更改常量的值。 这是非法的,会导致编译错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.