在下面的代码示例中,如何从内部作用域访问全局变量,如何从主函数和最内部作用域到达全局字符串X,并且,一旦我们将其退出到主作用域或其他作用域,那么最内部的作用域是否也是可访问的?
#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是:
1 global
2 main scope
3 main scope
4 inner scope
5 main scope发布于 2015-02-06 08:47:45
使用::x可以达到全局范围,如下所示:
#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;
}这给了你:
1 global
global
2 main scope
global
3 main scope
global
4 inner scope
global
5 main scope困难的部分实际上是到达中间作用域,例如当您使用内部作用域时的main scope。
这样做的一种方法是引用:
#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";
}
}这意味着:
1a outer
2a outer
2b middle
3a outer
3b middle
3c inner但是,作为一个好建议,如果你:
而且,对于内部作用域中的变量,一旦您离开该作用域,即使有引用,它们也不再可用(您可以将它们复制到一个范围更大的变量中,但这与访问内作用域变量不同)。
https://stackoverflow.com/questions/28361736
复制相似问题