【问题标题】:How to access function scope variables in c++? [duplicate]如何在 C++ 中访问函数范围变量? [复制]
【发布时间】:2018-07-27 01:25:57
【问题描述】:

可以使用 :: 运算符在函数内访问全局范围的变量。由于全局范围没有名称,因此 :: 的左侧可能为空。我将如何访问在函数范围中定义的变量,该变量稍后在函数本身的块中被覆盖。在下面的代码中,我将如何访问初始化为 1 的变量?

extern int reused = 0;
int main()
{
    int reused = 1;
    {
        int reused = 2;
        cout << reused << endl; // how to get the reused inited to 1 here?
    }
}

【问题讨论】:

  • 也许function.reused?
  • 也许通过使用不同的变量名?
  • 你不能。就这么简单。
  • 我原以为你会收到有关阴影的警告

标签: c++ scope-resolution


【解决方案1】:

您可以使用::reusedmain 内的任何位置访问全局reused。但是,无法在声明第三个reused 的块内使用第二个reused。该语言没有为此提供机制。

【讨论】:

    猜你喜欢
    • 2012-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2018-10-09
    相关资源
    最近更新 更多