gpt4 book ai didi

C++ 嵌套作用域访问

转载 作者:太空狗 更新时间:2023-10-29 20:10:07 26 4
gpt4 key购买 nike

我最近在 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++ 作用域。

最佳答案

这是一个名称隐藏问题。和

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

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

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

您可以使用 scope resolution operator ::为此,例如::str,在全局范围内引用名称str

关于C++ 嵌套作用域访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41842637/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com