【发布时间】:2019-09-12 14:05:41
【问题描述】:
我是 C++ 的初学者。我从“加速 c++”一书中了解到块作用域内的 const 变量。这意味着“const变量将在作用域结束于}时被销毁。
但在测试中:常量字符串变量s 是在第一个块内定义的。在第二个块中,还定义了s。当第二个s 被打印出来时,第一个块的s 还没有被销毁。
我认为程序是无效的,但是当我编译程序时结果是完全正确的。我不知道为什么会这样。请帮助我理解代码。
#include <iostream>
#include <string>
int main()
{
const std::string s = "a string";
std::cout << s << std::endl;
{
const std::string s = "another string";
std::cout << s << std::endl;
}
return 0;
}
结果是
一个字符串
另一个字符串
【问题讨论】:
-
这被称为“阴影”,你可以阅读它here。
-
阅读范围和block scope。
-
const与变量生命周期无关,变量在其作用域结束时被销毁,无论是否为const
标签: c++ variables scope constants declaration