瞭解範圍很重要。循環和函數創建一個範圍,並且它們總是可以在更高的範圍訪問事物;然而,事情不能從更小的範圍訪問。對象在其作用域的整個期間都存在,並且該作用域內的任何對象都可以訪問它們。
// Global scope:
int g = 0; // everything in this file can access this variable
class SomeClass
{
// Class scope
int c = 0;
void ClassFunction()
{
// ClassFunction scope
// Here we can access anything at global scope as well as anything within this class's scope:
int f = 0;
std::cout << g << std::endl; // fine, can access global scope
std::cout << c << std::endl; // fine, can access class scope
std::cout << f << std::endl; // fine, can access local scope
}
// Outside of ClassFunction, we can no longer access the variable f
};
void NonClassFunction()
{
// NonClassFunction scope
// We can access the global scope, but not class scope
std::cout << g << std::endl;
int n1 = 0;
for (...)
{
// New scope
// Here we can still access g and n1
n1 = g;
int x = 0;
}
// We can no longer access x, as the scope of x no longer exists
if (...)
{
// New scope
int x = 0; // fine, x has not been declared at this scope
{
// New scope
x = 1;
g = 1;
n1 = 1;
int n2 = 0;
}
// n2 no longer exists
int n2 = 3; // fine, we are creating a new variable called n2
}
}
希望這有助於向你解釋範圍。考慮到所有這些新信息,答案是肯定的:您可以在for循環中訪問您的變量,因爲這些變量的範圍在內部範圍內保持不變。
來源
2015-04-30 00:29:48
Tas
你是說你不能在循環內使用'myage'變量嗎? – Cristik
如果你不能使用它們,你會得到一個編譯器錯誤。 – chris
@chris:讓我們不要跳入苛刻的結論,也許他正在使用一個更新的編譯器:) – Cristik