全球范围可以通过使用::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
但是,正如好的建议,你会发现,你不会有任何地方在附近有很多问题,如果你:
- 以更智能的方式命名你的变量,以便避免冲突;和
- 避免像瘟疫全局变量:-)
而且,作为在内部范围的变量,它们不再是可一旦你离开是范围,甚至与参考(您可以复制他们到一个更大范围的变量,但这不同于访问内部范围变量)。
通过使用范围操作符'::',如':: x'表示全局变量'x'。 – 2015-02-06 08:46:17
请勿为所有变量使用相同的名称。 – Theolodis 2015-02-06 08:46:32
@Theolodis当然,我只是想了解范围的想法 – 2015-02-06 11:25:03