【问题标题】:How to understand the const variable between different block scopes如何理解不同块作用域之间的 const 变量
【发布时间】: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


【解决方案1】:

用以下方式放大你的程序

#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 之前声明并且属于全局命名空间,那么您可以使用它的限定名称来访问该变量。

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

【讨论】:

  • 感谢您的回复,但是,还有两个问题,“限定名”和“非限定名”是什么意思?另一个,你的代码中的“::s”是什么意思?非常感谢你!!
猜你喜欢
  • 2023-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 2014-10-11
  • 2016-02-21
  • 1970-01-01
相关资源
最近更新 更多