每个派生类的静态变量 [英] static variable for each derived class

查看:161
本文介绍了每个派生类的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

子类化时覆盖静态变量

所有派生自基类的类。任何这些派生类都声明相同的静态变量。

I have a set of classes that are all derived from a base class. Any of these derived classes declare the same static variable. It is however specific to each of the derived classes.

Consider the following code.

请考虑以下代码。 code> class Base {
// TODO:在某种程度上声明一个虚拟静态变量?
bool foo(int y){
return x> y; //错误:'x'未在此范围中声明
}
};

class A:public Base {
static int x;
};

class B:public Base {
static int x;
};

class C:public Base {
static int x;
};

int A :: x = 1;
int B:x = 3;
int C :: x = 5;

int main(){}

class Base { // TODO: somehow declare a "virtual" static variable here? bool foo(int y) { return x > y; // error: ‘x’ was not declared in this scope } }; class A : public Base { static int x; }; class B : public Base { static int x; }; class C : public Base { static int x; }; int A::x = 1; int B::x = 3; int C::x = 5; int main() {}

实现一些逻辑,这需要知道派生类特定 x 。任何派生类都有此变量。因此,我想能够在基类范围引用这个变量。

In my base class I wanted to implement some logic, that requires the knowledge of the derived-class-specific x. Any of the derived classes has this variable. Therefore I would like to be able to refer to this variable at base class scope.

如果它是一个简单的成员变量,这不会是一个问题。然而,在语义上,变量确实不是派生类实例的属性,而是派生类本身的属性。因此它应该是一个静态变量。

This wouldn't be a problem if it were a simple member variable. However, semantically, the variable is indeed not a property of the derived class' instance, but rather of the derived class itself. Therefore it should be a static variable.

UPDATE 我需要类层次结构来保持其多态性。也就是说,我的所有派生类的实例需要是一个公共基类的成员。

UPDATE I need the class hierarchy to preserve its polymorphic nature. That is, all my derived class' instances need to be members of a common base class.

然而,如何从基类方法中获取这个变量?

Then however, how can I get my hands on this variable from the base class method?

推荐答案

您可以使用奇怪的经常性模板模式

// This is the real base class, preserving the polymorphic structure
class Base
{
};

// This is an intermediate base class to define the static variable
template<class Derived>
class BaseX : public Base
{
    // The example function in the original question
    bool foo(int y)
    { 
        return x > y;
    }

    static int x;
};

class Derived1 : public BaseX<Derived1>
{
};

class Derived2 : public BaseX<Derived2>
{
};

现在,类 Derived1 Derived2 每个都有一个 static int x 可以通过中间基类获得!此外, Derived1 Derived2 都将通过绝对基类共享公共功能 code>。

Now classes Derived1 and Derived2 will each have a static int x available via the intermediate base class! Also, Derived1 and Derived2 will both share common functionality via the absolute base class Base.

这篇关于每个派生类的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆