3

我派生的类在某些常量属性上有所不同。在所有派生类中,我都有一个返回属性的函数。有没有办法将 get_x 函数移到基类中以删除重复项?我查看了这个线程和很多谷歌搜索,但我找不到我想要的东西: C++:在派生类中用不同的值初始化基类常量静态变量?

class Derived1: public Base{
    static const attribute x = SOME_ATTRIBUTE1;
    attribute get_x(){
        return x;
    }
};

class Derived2: public Base{
    static const attribute x = SOME_ATTRIBUTE2;
    attribute get_x(){
        return x;
    }
};

我希望它看起来像这样,但这不起作用,因为 x 没有在 base.xml 中定义。我也尝试过 extern、static const attribute x 等。

class Derived1: public Base{
    static const attribute x = SOME_ATTRIBUTE1;
};

class Derived2: public Base{
    static const attribute x = SOME_ATTRIBUTE2;
};

class Base{
    attribute get_x(){
        return x;
    }
};

谢谢。

4

3 回答 3

2

有点笨拙,但您可能会使用类似于以下内容的内容来执行此操作:

template <attribute x> class Base
{
    public:
        attribute get_x ( ) { return x; }
};

class Derived1 : public Base<SOME_ATTRIBUTE_1>
{
    ...
};

class Derived2 : public Base<SOME_ATTRIBUTE_2>
{
    ...
};

类似于卡尔的答案,但保留了继承/派生的关系(嗯,几乎 - 请参阅下面的@visitor 评论)。

另一方面,是否有理由不进行简单的覆盖?例如:

class Base
{
    public:
        virtual attribute get_x ( ) = 0;
};

class Derived1 : public Base
{
    public:
        attribute get_x ( ) { return SOME_ATTRIBUTE_1; };
};

class Derived2 : public Base
{
    public:
        attribute get_x ( ) { return SOME_ATTRIBUTE_2; };
};

编辑:请注意,模板方法可以扩展到所需的任意数量的属性,如下所示:

template <attribute1 x, attribute2 y ...> class Base
{
    public:
        attribute get_x ( ) { return x; }
        attribute get_y ( ) { return y; }
        ...
};

具有每个属性是类的属性的另一种解决方案可能如下:

class Base
{
    public:
        Base (attribute newX) : x(newX) { }
        attribute get_x ( ) { return x; };
    protected:
        const attribute x;
};

class Derived1 : public Base
{
    public:
        Derived1 ( ) : Base(SOME_ATTRIBUTE_1) { }
};

class Derived2 : public Base
{
    public:
        Derived2 ( ) : Base(SOME_ATTRIBUTE_2) { }
};

在这里,每个Derived都有一个该类独有的常量属性。const如果您愿意,当然可以放弃。

于 2011-02-23T04:23:26.733 回答
1

好吧,取决于类的其余部分,它可能是模板而不是多态继承的一个很好的用例:

template <attribute X>
class Base{
    attribute get_x(){
        return X;
    }
}

typedef Base<SOME_ATTRIBUTE1> Derived1;
typedef Base<SOME_ATTRIBUTE2> Derived2;
于 2011-02-23T04:21:46.620 回答
1
#include <iostream>
#include <typeinfo>

enum attribute {SOME_ATTRIBUTE1, SOME_ATTRIBUTE2};

class Base
{
public:
    virtual attribute get_x() = 0;
};

template <attribute Attr>
class Derived : public Base
{
public:
    virtual attribute get_x() {return Attr;}
};

typedef Derived<SOME_ATTRIBUTE1> Derived1;
typedef Derived<SOME_ATTRIBUTE2> Derived2;

int main()
{
    std::cout << typeid(Derived1().get_x()).name() << '\n';
    return 0;
}
于 2011-02-23T15:48:34.587 回答