zoukankan      html  css  js  c++  java
  • 关于静态变量

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

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

     1 #include <stdio.h>
     2 
     3 class A{
     4 
     5 public:
     6 
     7 A(){printf("constructor of A
    ");}
     8 
     9 ~A(){printf("destruction of A
    ");}
    10 
    11 };
    12 
    13 class B{
    14 
    15 public:
    16 
    17 static A a;
    18 
    19 B(){printf("constructor of B
    ");}
    20 
    21 };
    22 
    23 A B::a;
    24 
    25 int main()
    26 
    27 {
    28 
    29 printf("main
    ");
    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
    ");}
     8 
     9 ~A(){printf("destruction of A
    ");}
    10 
    11 };
    12 
    13 int caller()
    14 
    15 {
    16 
    17 static A a;
    18 
    19 printf("caller
    ");
    20 
    21 return 0;
    22 
    23 }
    24 
    25 int main()
    26 
    27 {
    28 
    29 printf("main
    ");
    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
    ");}
     8 
     9 ~A(){printf("destruction of A
    ");}
    10 
    11 };
    12 
    13 static A a;
    14 
    15 int main()
    16 
    17 {
    18 
    19 printf("main
    ");
    20 
    21 return 0;
    22 
    23 }

     

  • 相关阅读:
    TiDB架构特性
    TiDB入门
    ansible安装nginx
    linux命令之cowsay
    KeepAlived 搭建高可用的HAProxy集群
    HAProxy 实现镜像队列的负载均衡
    RabbitMQ高可用集群介绍
    docker安装phpMyAdmin
    centos7安装RabbitMQ
    Vim轻量级查看Java代码
  • 原文地址:https://www.cnblogs.com/xiaoerhei/p/3937676.html
Copyright © 2011-2022 走看看