c++ - 每个派生类的静态变量

标签 c++ oop static

<分区>

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

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

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

但是,我怎样才能从基类方法中获取这个变量呢?

最佳答案

您可以使用 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 共享通用功能。

关于c++ - 每个派生类的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12796580/

相关文章:

c++ - 运算符重载的基本规则和惯用法是什么?

c++ - 无法让 SFML 音乐工作

python - 在类内访问 `__attr` 时,名称修改如何工作?

C++:静态变量不随静态 set() 函数改变

c++ - 将类更改为静态类有些奇怪

.net - 如何将 GetMethod 用于静态扩展方法

c++ - 显示字符串的地址

c++ - C++中的错误检查

c - 使用 C 语言进行数据封装的 OOP 编程

python - 在 Python 中继承方法的文档字符串