每个派生类的静态变量

moo*_*eep 11 c++ oop static

可能重复:
子类化时覆盖静态变量

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

请考虑以下代码.

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() {}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Mar*_*ram 21

您可以使用奇怪的重复模板模式.

// 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>
{
};
Run Code Online (Sandbox Code Playgroud)

现在的类Derived1Derived2每个都将static int x通过中间基类提供!此外,Derived1Derived2都将通过绝对的基类共享公共功能Base.

  • 好吧,我已经删除了"需要"字样,尽管我仍然觉得你很苛刻.该解决方案比下面提供的其他解决方案更整洁. (2认同)

Min*_*n91 5

具有虚拟吸气功能

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);
}
Run Code Online (Sandbox Code Playgroud)