【问题标题】:How many instances are there, of static variables declared in a method?在方法中声明的静态变量有多少个实例?
【发布时间】:2012-07-06 13:32:28
【问题描述】:

在这种情况下,静态变量应该只有一个或零个实例。这取决于是否调用了f()

void f() 
{
    static int a;
}

但是如果f() 是一个方法,那么静态变量有多少个实例呢?

class A
{
    void f()
    {
        static int a;
    }
};

【问题讨论】:

    标签: c++ static static-methods static-members


    【解决方案1】:

    与函数相同:0或1。也很容易检查:

    class A
    {
    public:
        void f()
        {
            static int a = 0;
            ++a;
            cout << a << endl;
        }
    };
    
    
    int main()
    {
        A a;
        a.f();
        a.f();
        A b;
        b.f();
    }
    

    输出:

    1
    2
    3
    

    但是,如果您从 class A 派生并像这样将函数设为虚拟:

    class A
    {
    public:
        virtual void f()
        {
            static int a = 0;
            ++a;
            cout << a << endl;
        }
    };
    
    class B:public A
    {
    public:
        void f()
        {
            static int a = 0;
            ++a;
            cout << a << endl;
        }
    };
    

    那么a 变量对于基类和每个派生类将是不同的(因为函数也不同)。

    【讨论】:

      【解决方案2】:

      同样...作为成员函数与作为静态局部函数是正交的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-10
        • 2011-03-23
        • 2014-02-03
        • 2021-08-24
        • 1970-01-01
        • 2012-04-10
        • 1970-01-01
        相关资源
        最近更新 更多