本文介绍了静态变量在静态方法中的基类和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这些C ++类:
Baser基因来保留多态性,如Neil和Akanksh所指出的。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)?
解决方案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.
这篇关于静态变量在静态方法中的基类和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!