作用域和可见性

 1 //作用域与可见性
 2 #include<iostream>
 3 using namespace std;
 4 int i;   //文件作用域
 5 int main()
 6 {   i=5;
 7      {  int i;  //块作用域
 8          i=7;
 9          cout<<"i="<<i<<endl;  //输出7
10      }
11      cout<<"i="<<i;   //输出5
12     // while(1);
13      return 0;
14 }
15 
16 
17 
18 //对象的生存期
19 #include<iostream>
20 using namespace std;
21 void fun();
22 void main()
23 {   fun();
24      fun();
25 }
26 void fun()
27 {   static int a=1;
28      int i=5;
29      a++;
30      i++;
31      cout<<"i="<<i<<",a="<<a<<endl;
32 }
33 运行结果:
34 i=6, a=2
35 i=6, a=3
36 i是动态生存期
37 a是静态生存期
38 
39 
40 
41 
42 #include<iostream>
43 using namespace std;
44 class Application
45 { public:
46      void f(); void g();
47   private:
48      int global;
49 };
50 void Application::f()
51 {  global=5;}
52 void Application::g()
53 {  cout<<global<<endl;}
54 
55 int main()
56 {
57    Application  MyApp;
58    MyApp.f();
59    MyApp.g();
60    return 0;
61 }

 

posted @ 2012-08-30 18:41  加拿大小哥哥  阅读(380)  评论(0编辑  收藏  举报