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静态变量之间共享A和B,或将他们中的每一个都有它自己的独立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指出的那样.
| 归档时间: |
|
| 查看次数: |
3389 次 |
| 最近记录: |