我最近在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”将被销毁,因此在那之后它将不可用,因此第二个print 将主要的“str”作为其参数。
但是,我知道主“str”实际上在 IF 中可用,或者至少应该是可用的,但问题是如何从 IF 语句中访问主“str”?
我怎么能从 main 和/或 if 内部访问全局“str”?
我知道只使用不同的名称会更简单,但是这个问题不是针对特定的实际应用程序,而是为了更好地理解 c++ 范围。