全球範圍可以通過使用::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