C ++嵌套作用域访问 [英] C++ Nested Scope Accessing

查看:134
本文介绍了C ++嵌套作用域访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在 cppreference中看到了这段代码:

string str="global scope";

void main()
{
    string str="main scope";
    if (true){
        string str="if scope";
        cout << str << endl;
    }
    cout << str << endl;
}

哪个输出:

if scope
main scope

这很好,我了解整个嵌套的作用域,并且我知道当堆栈在语句末尾将其展开时,if作用域内的'str'将被销毁,因此此后将不再可用,因此,第二个打印文件将主'str'作为其参数.

This is fine, I understand the whole nested scope thing, and I know that the 'str' inside the if scope will be destroyed when the stack unwinds it at the end of the statement, so it wont be available after that, hence the second print takes the main 'str' as its argument.

但是,我知道主要的'str'实际上可以在IF内使用,或者至少应该可以使用,但是问题是我如何从IF语句内部访问主要的'str'?

However, I know that the main 'str' is in fact available inside the IF, or at least it should be, but the question is how can I access the main 'str' from inside the IF statement?

我该如何从main和/或if内部访问全局'str'?

我知道只使用不同的名称会更简单,但是这个问题不是针对特定的实际应用,而是为了更好地理解c ++范围.

I know it would be simpler to just use different names, but this question is not for a specific practical application, but rather for a better understanding of c++ scopes.

推荐答案

这是一个隐藏名称的问题.还有

This is a name-hiding issue. And

如何从IF语句内部访问主'str'?

how can I access the main 'str' from inside the IF statement?

不幸的是,这是不可能的.无法访问被隐藏的这些本地名称.

Unfortunately it's impossible. There's no way to access these local names being hiden.

又如何从main和/或if内部访问全局'str'?

And how could I access a global 'str' from inside the main and/or the if?

您可以使用范围解析运算符:: ,例如::str,在全局范围内引用名称str.

You can use scope resolution operator :: for it, e.g. ::str, which refers to the name str in the global scope.

这篇关于C ++嵌套作用域访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆