【发布时间】:2017-03-20 20:32:22
【问题描述】:
我经常遇到这样一种情况,我们创建了一个作用于某个枚举的类,但后来我们派生并且我们希望在不更改基类的情况下为枚举添加更多值。
我从 2009 年就看到了这个问题: Base enum class inheritance
但是,我知道在 C++11、14、17 中对枚举进行了许多更改。 这些更改是否允许将枚举从基类扩展到派生类?
class Base
{
enum State {STATE_1, STATE_2, STATE_3};
};
class Derived : public Base
{
enum State {STATE_4};
};
...我们希望派生有一个枚举来描述它可以处于的状态,它们是:STATE_1、STATE_2、STATE_3 和 STATE_4。我们真的不想更改基类中的枚举,因为其他派生类可能不具备处于 STATE_4 的能力。我们也不想创建一个新的枚举,因为我们已经在 Base 中有一个用于 State 的枚举。
我们是否仍然使用静态 const 值来代替 8 年后实现这一目标?
class Base
{
static int STATE_1= 0;
static int STATE_2= 1;
static int STATE_3= 2;
};
class Derived : public Base
{
static int STATE_4= 3;
};
【问题讨论】:
-
不,任何枚举更改都与 nothing 相关。
-
enum在 17 年 11 月 14 日发生了很大变化吗?我知道他们引入了强类型enum class,但我很确定普通的enum基本保持不变。