1

Suppose I have a base class with a method to return a state of its instance:

enum STATE {ALIVE, DEAD}

class BASE{
    virtual STATE doThingsAndReturnStatus() {...};
}

Now I have my derived class which may have additional state, e.g. HALFDEAD. It looks to me it is difficult to get the interface consistent unless for each derived class I need to add a STATE globally. (i.e. add new items into the definition of STATE in class BASE). My question is how to achieve this type of extending for derived class without touching on the based class or the file contains it.)

It is not necessary to restrict the discussion on "enum" only.

I found a related thread here. But it doesn't fit into my needs:

Extending enums in C++?

4

2 回答 2

3

您可以用enumor intor stringor floator some such 替换。

但是,这也可能不是一个好主意。假设我们可以扩展enum[在具有此功能的 C++ 的虚构版本中] ,因为getMyStatus它是一个虚函数,它被设计为从不知道派生类细节的通用代码中调用。因此,如果您编写如下内容:

for(iter : baseClassContainter)
{
    status = iter->getMyStatus();
    switch(status)
    {
       case DEAD: 
            ... do some stuff here. 
            break;

       case ALIVE:
            ..... do some stuff here ... 

    }
}

这段代码应该如何处理“HALFDEAD”?它甚至不知道存在这样的值,因为[在我们支持这一点的想象语言中]它只存在于派生类中......

于 2013-06-17T20:57:46.087 回答
1

你可以接近:

constexpr STATE HALFDEAD = static_cast<STATE>(DEAD+1);

但是您有责任确保值(DEAD+1以上)不等于任何其他枚举数。

于 2013-06-17T21:39:35.580 回答