static variable for each derived class [duplicate]

2019-01-24 06:44发布

Possible Duplicate:
Overriding static variables when subclassing

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.

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() {}

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 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?

标签: c++ oop static
2条回答
smile是对你的礼貌
2楼-- · 2019-01-24 06:59

With a virtual getter function

class Base {
public:
    bool foo(int y) const{ 
        return getX() > y;
    }
    virtual int getX() const = 0;
};

class A : public Base {
    static const int x;
    int getX() const {return x;}
};

class B : public Base {
    static const int x;
    int getX() const {return x;}
};

class C : public Base {
    static const int x;
    int getX() const {return x;}
};

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

int main()
{
    C c;
    bool b = c.foo(3);
}
查看更多
甜甜的少女心
3楼-- · 2019-01-24 07:20

You can use the Curiously recurring template pattern.

// 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>
{
};

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.

查看更多
登录 后发表回答