【问题标题】:Polymorphic static const member variables in an ABC?ABC中的多态静态const成员变量?
【发布时间】:2011-09-26 09:56:26
【问题描述】:

我有一个相当奇怪的情况,我希望能够定义一些 ABC 的子类可以覆盖的常量。

struct A {
    static const int a = 20;
    virtual int func() = 0;
};
struct B : public A {
    static const int a = 3;
    int func() { return 5; }
};
struct C : public A {
    static const int a = 4;
    int func() { return 3; }
};

不幸的是,如果我使用A *aPtr = new BaPtr->a 将返回 20,而不是 3。

我看到的一种解决方法是单行函数(沿着上面示例中的func 行),但从概念上讲,常量的语法更适合这种特殊情况。是否有一种语法上合理的方法来解析在运行时使用哪些常量,而调用代码在初始对象创建后不需要知道任何内容?

【问题讨论】:

  • 想要这个的原因可能是有缺陷的:一个常量应该是,嗯,constant。它有时不是恒定的,有时是其他的。同样,静态成员是类的属性,而不是实例,因此它们在继承中没有任何作用,这是一个基于 instance 的概念。

标签: c++ static polymorphism constants


【解决方案1】:

常量,尤其是静态常量,不能像您要求的那样被覆盖。您将不得不使用虚函数:

struct A {
    virtual int get_a() { return 20; }
    int func() = 0;
};

struct B : public A {
    virtual int get_a() { return 3; }
    int func() { return 5; }
};

struct C : public A {
    virtual int get_a() { return 4; }
    int func() { return 3; }
};

另一种选择是为常量使用模板:

template< const int a_value = 20 >
struct A {
    static const int a = a_value;
    int func() = 0;
};

struct B : public A<3> {
    int func() { return 5; }
};

struct C : public A<4> {
    int func() { return 3; }
};

【讨论】:

  • 对于模板版本,应该注意BC 类现在完全不相关,因为它们具有不同的基类。
【解决方案2】:

你可以从例子中得到答案! :) 只需声明一个类似get_a() 的方法,即virtual 并覆盖它。

struct A {
    static const int a = 20;
    virtual int get_a() const { return a; }  // <--- for A
};
struct B : public A {
    static const int a = 3;
    virtual int get_a() const { return a; }    // <--- for B
};
struct C : public A {
    static const int a = 4;
    virtual int get_a() const { return a; }    // <--- for C
};

另请注意,在 C++ 中,只有方法可以被覆盖,而变量则不能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多