C++ 11-作用域和全局变量

A_M*_*tar 0 scopes c++11

如何从内部作用域访问全局变量,给定以下代码示例,如何从主函数和最内部作用域访问全局字符串 X,一旦我们退出它,最内部作用域也是可访问的主要范围还是其他范围?

#include <iostream>
#include <string>
std::string x = "global";
int counter = 1;

int main()
{
    std::cout <<counter ++ << " " << x << std::endl;
    std::string x = "main scope";
    std::cout <<counter ++ << " "  << x << std::endl;
    {
        std::cout <<counter ++ << " " << x << std::endl;
        std::string x = "inner scope";
        std::cout <<counter ++ << " " << x << std::endl;
    }
    std::cout <<counter++ << " "  << x << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

目前的 cout 是:

1 global
2 main scope
3 main scope
4 inner scope
5 main scope
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 5

可以通过使用 达到全局范围::x,如下所示:

#include <iostream>
#include <string>

std::string x = "global";
int counter = 1;

int main()
{
    std::cout << counter++ << " " << x << std::endl;
    std::string x = "main scope";
    std::cout << "  " << ::x << std::endl;
    std::cout << counter++ << " "  << x << std::endl;
    {
        std::cout << "  " << ::x << std::endl;
        std::cout << counter++ << " " << x << std::endl;
        std::string x = "inner scope";
        std::cout << "  " << ::x << std::endl;
        std::cout << counter++ << " " << x << std::endl;
    }
    std::cout << "  " << ::x << std::endl;
    std::cout << counter++ << " "  << x << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这给你:

1 global
  global
2 main scope
  global
3 main scope
  global
4 inner scope
  global
5 main scope
Run Code Online (Sandbox Code Playgroud)

困难的部分实际上是到达中间范围,例如main scope当您在内部范围内时。

一种方法是使用参考文献:

#include <iostream>
#include <string>

std::string x = "outer";

int main()
{
    std::cout << "1a " << x << "\n\n";

    std::string x = "middle";
    std::cout << "2a " << ::x << '\n';
    std::cout << "2b " << x << "\n\n";

    {
        std::string &midx = x;  // make ref to middle x.
        std::string x = "inner";  // hides middle x.
        std::cout << "3a " << ::x << '\n';
        std::cout << "3b " << midx << '\n';  // get middle x via ref.
        std::cout << "3c " << x << "\n\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

这使:

1a outer

2a outer
2b middle

3a outer
3b middle
3c inner
Run Code Online (Sandbox Code Playgroud)

但是,作为一个好建议,如果您执行以下操作,您会发现您不会遇到那么多问题:

  • 更明智地命名变量以避免冲突;和
  • 避免像瘟疫一样的全局变量:-)

而且,对于内部作用域中的变量,一旦离开该作用域,即使有引用,它们也不再可用(您可以将它们复制到具有更大作用域的变量,但这与访问内部作用域变量不同) 。