09-05B——static的用法和作用

作用

  1. 隐藏

不论是static函数orstatic变量,当多个文件被同时编译的时候,所有没有static前缀的全局变量和函数都有全局可见性

  1. 保持变量内容的持久

如果一个变量存储在静态数据区,那么它会在程序刚开始运行的时候就完成初始化,这也是唯一的一次初始化。

  • 一共有2种变量存储在静态存储区:全局变量和static变量。
  1. 默认初始化为0

这个是针对static变量而言的。全局变量也会初始化为0,因为在静态数据区,内存中所有的字节默认值均是0x00

  1. C++的类成员声明static

实战

  1. 函数中的静态变量

代码

#include <iostream>
#include <string>

using namespace std;

void demo()
{
    static int cnt = 0;
    cout << cnt << ' ';

    cnt ++;
}

int main()
{
    for (int i = 0; i < 5; i ++ ) demo();
    return 0;
}

  1. 类中的静态变量

类中的静态变量应该是用户使用类外的类名和范围解析运算符显式初始化

代码

#include <iostream>

using namespace std;

class Apple
{
public:
    static int i;

    Apple ()
    {

    };
};

int Apple::i = 1;

int main()
{
    Apple obj1;
    Apple obj2;
    Apple obj;

    cout << obj.i << endl;

    obj1.i = 2;
    obj2.i = 3;

    cout << obj1.i << endl << obj2.i << endl;
}

输出

image.png

  1. 类对象为静态
  • 对象是非静态的
#include <iostream>

using namespace std;

class Apple
{
    int i;
public:
    Apple ()
    {
        i = 0;
        cout << "Inside Ctor\n";
    }

    ~Apple ()
    {
        cout << "Inside Dtor\n";
    }

};

int main()
{
    int x = 0;
    if (x == 0) Apple obj;

    cout << "End of main\n";
}

输出

image.png
  • 将对象变成静态后
#include <iostream>

using namespace std;

class Apple
{
    int i;
public:
    Apple ()
    {
        i = 0;
        cout << "Inside Ctor\n";
    }

    ~Apple ()
    {
        cout << "Inside Dtor\n";
    }

};

int main()
{
    int x = 0;
    if (x == 0) static Apple obj;

    cout << "End of main\n";
}

输出

image.png

产生这样的原因是静态对象的范围是贯穿整个程序的生命周期的,所以要在main()结束后才调用dtor,非静态对象的范围只在if () Apple obj内部,所以结束后先调用的dtor


  1. 类中的静态函数

对于静态成员函数,可以直接使用类名和范围解析运算符调用,如果是非静态成员函数,这样则会报错。

#include <iostream>

using namespace std;

class Apple
{
public:
    static void printMsg()
    {
        cout << "Welcome to Apple!";
    }
};

int main()
{
    Apple::printMsg();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。