静态方法中的正常局部变量和静态局部变量之间有什么区别吗?

Is there any difference between normal and static local variables in static methods?

本文关键字:局部变量 什么 区别 之间 静态方法 静态      更新时间:2023-10-16
class A
{
    static void f(void)
    {
        int a;
        static int b;
    }
};

ab之间是否有任何(形式或实际)区别?

是的,请考虑以下事项:

#include <iostream>
using namespace std;
class A
{
    public:
    static void func()
    {
        static int a = 10;
        int b = 10;
        a++;
        b++;
        std::cout << a << " " << b << endl;
    }
};
int main() {
    A a, b;
    a.func();
    b.func();
    a.func();
    return 0;
}

afunc 的所有实例之间共享,但b是每个实例的本地,因此输出为:

11 11
12 11
13 11

http://ideone.com/kwlra3

是的,两者都是不同的。对于每个调用,将创建a,而b将只创建一次,并且对于类型为 A 的所有对象都是相同的。同样,我的意思是,所有对象共享一个b内存。