Static variables in static method in base class and inheritance

故事扮演 提交于 2019-11-30 15:21:17

问题


I have these C++ classes:

class Base
{
protected:
    static int method()
    {
        static int x = 0;
        return x++;
    }
};

class A : public Base
{

};

class B : public Base
{

};

Will the x static variable be shared among A and B, or will each one of them have it's own independent x variable (which is what I want)?


回答1:


There will only be one instance of x in the entire program. A nice work-around is to use the CRTP:

template <class Derived>
class Base
{
protected:
    static int method()
    {
        static int x = 0;
        return x++;
    }
};

class A : public Base<A> { };
class B : public Base<B> { };

This will create a different Base<T>, and therefore a distinct x, for each class that derives from it.

You may also need a "Baser" base to retain polymorphism, as Neil and Akanksh point out.




回答2:


There will only be one, shared by all three classes. If you want separate instances, you will have to create separate functions in the derived classes.




回答3:


I am pretty sure it will be shared between A and B.

If you want independent variables you can use the "Curiously Recurring Template Pattern" like:

template<typename Derived>
class Base
{
protected:
    static int method()
    {
        static int x = 0;
        return x++;
    }
};

class A : public Base<A>
{

};

class B : public Base<B>
{

};

Of course if you want polymorphism, you would have to define a even "Baser" class which Base derives from, as Base<A> is different from Base<B> like:

class Baser
{
};

template<typename Derived>
class Base : public Baser
{
protected:
    static int method()
    {
        static int x = 0;
        return x++;
    }
};

class A : public Base<A>
{};

class B : public Base<B>
{};

Now A and B can also be polymorphic.




回答4:


The former. Local static variables are bound to the method containing them, and method exists in one incarnation for all subclasses (in fact, for the whole app, even though the rest of the program does not see the method).




回答5:


The variable will be shared - it is per-function - in this case the function it belongs to is Base::method(). However if class Base was a template class you would get one instance of the variable for each instantiation (each unique set of actual template parameters) of class Base template - each instantiation is a new function.




回答6:


If you are making X as static then it will be shared among all the child classes. No issues with the function being static.



来源:https://stackoverflow.com/questions/2737013/static-variables-in-static-method-in-base-class-and-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!