gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:17:46 24 4
gpt4 key购买 nike

如果我声明一个常量变量

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

控制台显示值为 101

但是当我写这样的代码时:

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

有一个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?

是的,它们根本不同。

int const n=100; 
n++;

自增运算符显然不能申请一个const (ant) 变量,因为 const关键字防止它在初始定义后被更改。这就是发出编译器错误的原因。

在另一种情况下,变量本身没有改变,但在传递给 operator<<() 时会创建另一个临时值。的 std::cout .

关于c++ - 为什么将增量运算符应用于常量变量时​​会出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53239287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com