1Static的数据成员必须在类定义体的外部定义。

即在类内进行static 声明变量,在类的外部进行初始化,在main函数之前初始化,main结束销毁。

 1 #include <stdio.h>
 2 
 3 class A{
 4 
 5 public:
 6 
 7 A(){printf("constructor of A\n");}
 8 
 9 ~A(){printf("destruction of A\n");}
10 
11 };
12 
13 class B{
14 
15 public:
16 
17 static A a;
18 
19 B(){printf("constructor of B\n");}
20 
21 };
22 
23 A B::a;
24 
25 int main()
26 
27 {
28 
29 printf("main\n");
30 
31 B b;
32 
33 B c;
34 
35 return 0;
36 
37 }

关于静态变量

 

2、函数内部局部static变量

c++把函数内部static变量的初始化推迟到了caller的第一次调用,程序结束时销毁, 而不是像其他global变量一样,在main之前就进行它们的初始化。在C语言中是编译不通过的!

 1 #include <stdio.h>
 2 
 3 class A{
 4 
 5 public:
 6 
 7 A(){printf("constructor of A\n");}
 8 
 9 ~A(){printf("destruction of A\n");}
10 
11 };
12 
13 int caller()
14 
15 {
16 
17 static A a;
18 
19 printf("caller\n");
20 
21 return 0;
22 
23 }
24 
25 int main()
26 
27 {
28 
29 printf("main\n");
30 
31 caller();
32 
33 caller();
34 
35 return 0;
36 
37 }

 

 关于静态变量

3、全局static变量

我们并不能确定全局静态变量的初始化顺序!Effective C++中就是用在函数中返回局部静态变量的方式来解决全局变量初始化顺序未知的问题的。

全局静态变量在main函数开始前初始化,在main函数结束后销魂。

 1 #include <stdio.h>
 2 
 3 class A{
 4 
 5 public:
 6 
 7 A(){printf("constructor of A\n");}
 8 
 9 ~A(){printf("destruction of A\n");}
10 
11 };
12 
13 static A a;
14 
15 int main()
16 
17 {
18 
19 printf("main\n");
20 
21 return 0;
22 
23 }

 

 关于静态变量

相关文章:

  • 2022-12-23
  • 2021-08-14
  • 2022-12-23
  • 2021-09-19
  • 2021-10-05
  • 2022-12-23
  • 2022-01-04
猜你喜欢
  • 2021-06-22
  • 2022-12-23
  • 2021-09-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-19
相关资源
相似解决方案