Cons.W 2023-09-11 21:15 采纳率: 0%
浏览 148

c++静态变量为什么可以重复定义?


//返回局部变量引用
int& test01() {
    int a = 10; //局部变量
    return a;
}

//返回静态变量引用
int& test02() {
    static int a = 20;
    return a;
}

int main() {
    static int a = 20;

    //不能返回局部变量的引用
    int& ref = test01();
    cout << "ref = " << ref << endl;
    cout << "ref = " << ref << endl;

    //如果函数做左值,那么必须返回引用
    int& ref2 = test02();
    cout << "ref2 = " << ref2 << endl;
    cout << "ref2 = " << ref2 << endl;

    test02() = 1000;

    cout << "ref2 = " << ref2 << endl;
    cout << "ref2 = " << ref2 << endl;

    system("pause");

    return 0;
}

上述程序在运行过程中没有报错。但main函数中调用了两次test02()函数,test02()函数体中又定义了静态变量a,静态变量都存储在全局区,而全局区只在程序销毁时自动释放,意味着静态变量a只能被定义一次。而两次调用test02()的过程意味着静态变量a被定义了2次,那么为什么在main函数中静态变量a没有重复定义的报错?test02() = 1000是怎样运行的,将1000赋值给一个引用是存在解引用的过程吗?

  • 写回答

3条回答 默认 最新

  • &剑八& 2023-09-11 21:22
    关注

    main中定义的变量不是全局变量,可以理解成和普通的函数一样,定义了两次局部的仅是标志名一样,实际编译完分配的地址不一样。

    评论

报告相同问题?

问题事件

  • 创建了问题 9月11日