如何理解不同块作用域之间的const变量

How to understand the const variable between different block scopes

我是 C++ 初学者。我从 "accelerated c++" 一书中了解到块范围内的 const 变量。这意味着“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;
}

结果是

a string

another string

通过以下方式扩展您的程序

#include<iostream>
#include<string>

const std::string s = "a first string";

int main()
{
    std::cout << s << std::endl;

    const std::string s = "a string";
    std::cout << s << std::endl;

    {
        const std::string s = "another string";
        std::cout << s << std::endl;
    }

    std::cout << s << std::endl;
    std::cout << ::s << std::endl;

    return 0;
}

程序输出为

a first string
a string
another string
a string
a first string

内部作用域中的每个声明都隐藏了外部作用域中同名的声明(除了可以重载的函数名)。但是在外部作用域中声明的变量仍然存在。如果变量在命名空间内声明为第一个变量 s,它在 main 之前声明并且属于全局命名空间,那么您可以使用其限定名称来访问该变量。

当使用非限定名称时,编译器会从最近的范围开始搜索其声明。