如果我这样写:
#include <iostream>
int main()
{
using namespace std;
{int n;n=5;} cout<<n;
system("pause");
return 0;
}
编译器告诉我 n 未声明.然后我尝试将其设为静态,但编译器再次告诉我它未声明.声明为静态的变量没有程序范围吗?如果不是,我如何在这个程序中使用 n?
The compiler tells me that n is undeclared. Then I tried making it static, but again, the compiler tells me that it is undeclared. Doesn't a variable declated static have program scope? If not, how do I use n in this program?
您将范围与生命周期混淆了.静态变量的生命周期等于程序的生命周期,但它们仍然遵循基于声明位置的作用域规则.
You're confusing scope with lifetime. Static variables have a lifetime equal to the program's lifetime, but they still follow scoping rules based on where they are declared.
这篇关于C++ 中的局部/静态变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!