每个派生类的静态变量

时间:2012-10-09 09:12:19

标签: c++ oop static

  

可能重复:
  Overriding static variables when subclassing

我有一组类都是从基类派生的。这些派生类中的任何一个都声明了相同的静态变量。但是它对每个派生类都是特定的。

请考虑以下代码。

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。任何派生类都有此变量。因此,我希望能够在基类范围内引用此变量。

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

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

然而,我怎样才能从基类方法中获取这个变量?

2 个答案:

答案 0 :(得分:20)

您可以使用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>
{
};

现在,通过中间基类,每个类Derived1Derived2都可以使用static int x!此外,Derived1Derived2都将通过绝对基类Base共享通用功能。

答案 1 :(得分:4)

使用虚拟吸气功能

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);
}
相关问题