static关键字的3种用法

Class中的static的使用

  1. static成员

  2. static成员函数

    函数参数中没有隐含的this指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include "../src/include/local.h"

class Singleton {
public:
static Singleton& Get() { //静态成员函数
static Singleton s_Instance; //静态变量,每次调用Get()返回的都是同一个变量
return s_Instance;
}

void Hello() { std::cout << "Hello" << std::endl; }
};
//因为class中的其他普通变量都在构造函数中初始化,
//而static在类中初始化表示每个instance都有此成员,不符合语义,所以在全局作用域下初始化class中的static变量

class Singleton1 {
private:
static Singleton1* s_Instance;
public:
static Singleton1& Get() {
return *s_Instance;
}
};
Singleton1* Singleton1::s_Instance = nullptr;


int main()
{
Singleton::Get().Hello();
std::cin.get();
}

static 3种类型含义

  1. 多文件之间全局使用static限制变量的作用域在此编译单元内部.

    尝试链接其他编译单元作用域内部的符号报错undefined reference,未定义引用

    1
    2
    3
    /usr/bin/ld: /tmp/ccYxdT4J.o: in function `testFunc':
    main.c:(.text+0x1d): undefined reference to `add'
    collect2: error: ld returned 1 exit status

    main.c:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    #include <me.h>

    // int func(int,int);
    int add(int a,int b);

    int testFunc(int a,int b)
    {
    printf("%d\n",add(a,b));
    return 0;
    }

    int main()
    {
    testFunc(1,2);
    return 0;
    }

    unit.c:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    static int add(int,int);

    int func(int a,int b)
    {
    return add(a,b);
    }

    static inline int add(int a,int b)
    {
    return a + b;
    }
  1. class中static成员表示在所有 实例之间共享内存,

    static函数表示实现不带this指针,为类服务,而不是具体对象

  2. locate作用域,static表示变量将 在所在作用域内一直存在下去,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    #include <unistd.h>
    #include <time.h>
    #include "me.h"
    #include <string.h>

    void func1()
    {
    static int var = 1;
    printf("%d\n",var++);
    }

    void func2()
    {
    int var = 1;
    printf("%d\n",var++);
    }

    int main()
    {
    for(int i=0; i<5; i++)
    {
    func1();
    func2();
    printf("\n");
    }
    }