C++全局变量、局部静态变量是什么时候初始化的

#include <iostream>
using namespace std;

class test {
public:
    test() : num(100) {
        cout << "constructor " << num << endl;
    }
    test(int n) : num(n) {
        cout << "constructor " << num << endl;
    }
    test(const test &other)
    {
        this->num = other.num;
        cout << "copy constructor " << num << endl;
    }
    void Print()
    {
        cout << "num is " << num << endl;
    }
public:
    int num = 10;
};

void Func()
{
    static test local(22);
    local.Print();
}

test g_test(5);
test g_test1 = g_test;

int main() {
    cout << "hello world" << endl;
    test a(8);
    a.Print();
    
    test b;
    b.Print();
    
    g_test.Print();
    
    static test st(11);
    st.Print();

    return 0;
}

输出:

constructor 5
copy constructor 5
hello world
constructor 8
num is 8
constructor 100
num is 100
num is 5
constructor 11
num is 11

结论:

全局变量在main函数之前初始化的;

局部静态变量是在第一次使用的时候初始化的,不使用则不会初始化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值