对象的生存期
1、静态生存期
• 这种生存期与程序的运行期相同。
• 在文件作用域中声明的对象具有这种生存期。
• 在函数内部声明静态生存期对象,要冠以关键字
static。
2、动态生存期
• 块作用域中声明的,没有用static修饰的对象是动态生存期的对象(习惯称局部生存期对象)。
• 开始于程序执行到声明点时,结束于命名该标识符的作用域结束处。
#include <iostream>
using namespace std;
int i = 1;//i为全局变量,具有静态生存期
void other(){
static int a = 3;
static int b;
//a,b为静态局部变量,具有全局寿命,局部可见
//只第一次进入函数时被初始化
int c = 10;//局部变量,具有动态生存期,每次进入函数时都被初始化
a += 2; i += 32; c += 5;
cout << "---Other---\n";
cout << "i: " << i << "a: " << a << "b: " << b << "c: " << c << endl;
b = a;
}
int main(){
static int a;//静态局部变量,有全局寿命,局部可见。
int b = -10; // b, c为局部变量,具有动态生存期。
int c = 0;
cout << "‐‐‐MAIN‐‐‐\n";
cout<<" i: "<<i<<" a: "<<a<<" b: "<<b<<" c: "<<c<<endl;
c += 8; other();
cout<<"‐‐‐MAIN‐‐‐\n";
cout<<" i: "<<i<<" a: "<<a<<" b: "<<b<<" c: "<<c<<endl;
i += 10; other();
system("pause");
return<