基类和继承中的静态方法中的静态变量
我有这些 C++ 类:
class Base
{
protected:
static int method()
{
static int x = 0;
return x++;
}
};
class A : public Base
{
};
class B : public Base
{
};
x
静态变量是否会在 A
和 B
之间共享,或者它们每个都有自己独立的 < code>x 变量(这就是我想要的)?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
整个程序中只有一个
x
实例。一个很好的解决方法是使用 CRTP:这将创建一个不同的
Base< ;T>
,因此对于从它派生的每个类都有一个不同的x
。正如 Neil 和 Akanksh 指出的那样,您可能还需要一个“Baser”碱基来保留多态性。
There will only be one instance of
x
in the entire program. A nice work-around is to use the CRTP:This will create a different
Base<T>
, and therefore a distinctx
, for each class that derives from it.You may also need a "Baser" base to retain polymorphism, as Neil and Akanksh point out.
只有一个,由所有三个班级共享。如果您想要单独的实例,则必须在派生类中创建单独的函数。
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.
我很确定它将在 A 和 B 之间共享。
如果你想要独立变量,你可以使用“奇怪的重复模板模式”,例如:
当然,如果你想要多态性,你就必须定义一个甚至“Baser”类,它的 Base派生自,因为
Base
与Base
不同:现在 A 和 B 也可以是多态的。
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:
Of course if you want polymorphism, you would have to define a even "Baser" class which Base derives from, as
Base<A>
is different fromBase<B>
like:Now A and B can also be polymorphic.
前者。局部静态变量绑定到包含它们的方法,并且
method
存在于所有子类的一个化身中(事实上,对于整个应用程序,即使程序的其余部分看不到该方法)。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).该变量将被共享 - 它是每个函数 - 在这种情况下,它所属的函数是
Base::method()
。但是,如果class Base
是一个模板类,您将为class Base
模板的每个实例化(每组唯一的实际模板参数)获得一个变量实例 - 每个实例化都是一个新功能。The variable will be shared - it is per-function - in this case the function it belongs to is
Base::method()
. However ifclass Base
was a template class you would get one instance of the variable for each instantiation (each unique set of actual template parameters) ofclass Base
template - each instantiation is a new function.如果您将 X 设为静态,那么它将在所有子类之间共享。函数是静态的没有问题。
If you are making X as static then it will be shared among all the child classes. No issues with the function being static.