继承静态变量成员,但单独共享给各类继承类
如果类继承具有静态变量成员的基类,则将是它们唯一一个与继承的所有类共享的成员。
我有几种继承类,并且每个类都有很多实例。 我希望每个继承类都有一个单独的静态成员,并与其所有实例共享。
怎么办呢?
谢谢你,对我糟糕的英语感到抱歉。
编辑:
class a{
static int var;};
class b::a{};
class c::a{};
现在,我希望 b 的所有实例都具有相同的 var ,并且 c 的所有实例都具有相同的 var ,但是 var b 的 var 与 c 的 var 不同。
我再次对我的英语感到抱歉,如果你能纠正我,请纠正我。
If class inherits base class with static variable member, Will be their only one member that shared with all classes that inheritances.
I have few kinds inherits classes, and many instance of every one of them.
I want that every one of the inherits classes will have a separate static member, that shared with all of its instances.
How can it be done?
thank you, and sorry about my poor English.
edit:
class a{
static int var;};
class b::a{};
class c::a{};
Now, I want that all instances of b will have same var, and all instances of c will have same var , but the var of b will be different from the var of c.
I'm sorry again about my English, if you can correct me, please do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 CRTP 来解决这个问题:
AClass
和AnotherClass
都有一个variable
静态变量(类型为Member
) ,但第一个是来自YourBaseClass
的静态变量,另一个是来自YourBaseClass
的静态变量,这是两个不同的类。YourBaseBaseClass
是可选的,但如果您想使用YourBaseBaseClass*
指针操作AClass
和AnotherClass
,则需要它(你不能有YourBaseClass*
指针,因为YourBaseClass
不是一个类)。并记住定义那些静态变量。
You can work aroud that using CRTP :
AClass
andAnotherClass
both have avariable
static variable (of typeMember
), but the first one is a static variable fromYourBaseClass<AClass>
and the other is fromYourBaseClass<AnotherClass>
, which are two different classes.YourBaseBaseClass
is optional, but you need it if you want to manipulateAClass
andAnotherClass
using aYourBaseBaseClass*
pointer (you cannot have aYourBaseClass*
pointer, becauseYourBaseClass
is not a class).And remember to define those static variables.
在这种情况下,您不能将静态成员放入基类中。但您可以尝试将其放在派生类中,并通过调用基类中的静态方法来访问它。因此 Derived 和 Derived2 的实例可以共享不同的静态成员。如果派生类的 GetStaticValue() 方法被调用,则强制派生类定义一个名为 value 的静态成员。
You cannot put the static member in the base class in this scenario. But you can try to put it in the derived class and access it by calling an static method in the base class. So instances of Derived and Derived2 can share different static members. And you force the derived class to define a static member named value if its GetStaticValue() method is called.
静态成员与非静态成员不同。静态成员称为类变量,非静态成员称为实例变量。这是因为非静态成员属于特定对象(类的实例),而静态变量是共享的。
因此,静态成员不遵循相同的继承规则,并且仍然是定义它们的类的属性。
Static members are different from non-static members. Static members are called class variables, while non-static members are called instance variables. This is because non-static members belong to a particular object (instance of a class), while static variables are shared.
Thus, static members do not follow the same rules of inheritance, and remain property of the class that defines them.