C++语言程序设计 清华大学郑莉 例5-2变量的生存期与可见性 对 include<iostream> 象 using namespace std 的mnt=1;为全局变量,具有静态生存期 void main(void) 生{ static int a;∥静态局部变量,有全局寿命,局部可见 存 intb=10;∥b,c为局部变量,具有动态生存期。 int c=0: 期 void other(oid); cout<< -a-MAIN---n cout<<"i:"<<i<<"a:"<<a<<"b:"<<b<<"c:"<<c<<end C=C+8; other(; cout<< -a-MAIN---In cout<"i:"<<i<"a:"≤≤a<<"b:"<<b<<"c:"<<c<<endl; =i+10; other
C++语言程序设计 清华大学 郑莉 16 例5-2 变量的生存期与可见性 #include<iostream> using namespace std; int i=1; // i 为全局变量,具有静态生存期。 void main(void) { static int a; // 静态局部变量,有全局寿命,局部可见。 int b=-10; // b, c为局部变量,具有动态生存期。 int c=0; void other(void); cout<<"---MAIN---\n"; cout<<" i: "<<i<<" a: "<<a<<" b: "<<b<<" c: "<<c<<endl; c=c+8; other(); cout<<"---MAIN---\n"; cout<<" i: "<<i<<" a: "<<a<<" b: "<<b<<" c: "<<c<<endl; i=i+10; other(); } 对 象 的 生 存 期
void other(void) static int a=2. static int b; ∥la,b为静态局部变量,具有全局寿命,局部可见。 ∥)第一次进入函数时被初始化。 ntc=10;∥C为局部变量,具有动态生存期, ∥每次进入函数时都初始化。 a=a+2;i=i+32;c=c+5 cout<<"---OTHER---In cout<<"i:"<i<<"a:"<<a<<"b:"<<b<<"c "<<c<<end|
void other(void) { static int a=2; static int b; // a,b为静态局部变量,具有全局寿命,局部可见。 //只第一次进入函数时被初始化。 int c=10; // C为局部变量,具有动态生存期, //每次进入函数时都初始化。 a=a+2; i=i+32; c=c+5; cout<<"---OTHER---\n"; cout<<" i: "<<i<<" a: "<<a<<" b: "<<b<<" c: "<<c<<endl; b=a; } 17
运行结果 Main :1a:0b:-10c:0 other 33a:4b:0c:15 -L-MAIN i:33a:0b:-10c:8 other i:75a:6b:4c:15
运行结果: ---MAIN--- i: 1 a: 0 b: -10 c: 0 ---OTHER--- i: 33 a: 4 b: 0 c: 15 ---MAIN--- i: 33 a: 0 b: -10 c: 8 ---OTHER--- i: 75 a: 6 b: 4 c: 15 18
C++语言程序设计 清华大学郑莉 例5-3具有静、动态生存期对象的时钟程序 对“# ncludesiostream> 象 using namespace std 的 class Clock川时钟类声明 生{ubc:外部接口 Clock(; 存期 void SetTime(int NewH, int NewM, int News); ∥三个形参均具有函数原型作用域 void ShowTime( -Clocks private:∥有数据成员 int hour minute second
C++语言程序设计 清华大学 郑莉 19 例5-3具有静态、动态生存期对象的时钟程序 #include<iostream> using namespace std; class Clock //时钟类声明 {public: //外部接口 Clock(); void SetTime(int NewH, int NewM, int NewS); //三个形参均具有函数原型作用域 void ShowTime(); ~Clock(){} private: //私有数据成员 int Hour,Minute,Second; }; 对 象 的 生 存 期