如何从内部范围到达全局变量,给定以下代码示例,如何从main函数和最内部范围到达全局字符串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
答案 0 :(得分:4)
使用::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
hard 位实际上是在你使用内部范围时进入中间范围,例如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
但是,作为好的建议,如果您:
,您会发现在附近的任何地方都没有问题。而且,对于内部作用域中的变量,一旦你离开该作用域,它们就不再可用了,即使有一个引用(你可以将它们复制到一个范围更大的变量但不是与访问内部范围变量相同。)