【发布时间】:2017-01-25 02:56:57
【问题描述】:
我最近在 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”作为参数。
但是,我知道主“str”实际上在 IF 中可用,或者至少应该是,但问题是 我如何从 IF 语句中访问主“str”?
我如何从 main 和/或 if 内部访问全局“str”?
我知道只使用不同的名称会更简单,但这个问题不是针对特定的实际应用,而是为了更好地理解 c++ 作用域。
【问题讨论】:
-
cppreference 永远不会有“void main”。这甚至不会编译。
-
这取决于你的编译器
-
它不会在使用 gcc 和 clang 的 cppreference.com 上编译。
标签: c++ scope nested name-hiding