静态方法中的静态变量在基类和继承中

Meh*_*Meh 8 c++ inheritance static-methods static-variables

我有这些C++类:

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

class A : public Base
{

};

class B : public Base
{

};
Run Code Online (Sandbox Code Playgroud)

x静态变量之间共享AB,或将他们中的每一个都有它自己的独立x变量(这是我想要什么)?

Mar*_*tos 14

x整个程序中只有一个实例.一个很好的解决方法是使用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> { };
Run Code Online (Sandbox Code Playgroud)

这将为从中派生的每个类创建一个不同的Base<T>,因此是不同的x.

你可能还需要一个"Baser"基础来保留多态性,正如Neil和Akanksh指出的那样.

  • 但是如果需要的话,你没有得到的是多态性. (2认同)