首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C++ 11-作用域和全局变量

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

Stack Overflow用户
提问于 2015-02-06 08:44:11
回答 1查看 553关注 0票数 0

在下面的代码示例中,如何从内部作用域访问全局变量,如何从主函数和最内部作用域到达全局字符串X,并且,一旦我们将其退出到主作用域或其他作用域,那么最内部的作用域是否也是可访问的?

代码语言:javascript
运行
复制
#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;
}

目前的cout是:

代码语言:javascript
运行
复制
1 global
2 main scope
3 main scope
4 inner scope
5 main scope
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-06 08:47:45

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

代码语言:javascript
运行
复制
#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;
}

这给了你:

代码语言:javascript
运行
复制
1 global
  global
2 main scope
  global
3 main scope
  global
4 inner scope
  global
5 main scope

困难的部分实际上是到达中间作用域,例如当您使用内部作用域时的main scope

这样做的一种方法是引用:

代码语言:javascript
运行
复制
#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";
    }
}

这意味着:

代码语言:javascript
运行
复制
1a outer

2a outer
2b middle

3a outer
3b middle
3c inner

但是,作为一个好建议,如果你:

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

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28361736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档