枚举支持继承 [英] Enums support for inheritance

查看:59
本文介绍了枚举支持继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常遇到这样的情况:我们创建了一个对某些枚举起作用的类,但是后来我们派生了一个新的类,我们希望在不更改基类的情况下为枚举添加更多值.

我从2009年开始看到以下问题:基础枚举类继承

但是,我知道C ++ 11、14、17中的枚举有很多更改.这些更改是否允许将枚举从基类扩展到派生类?

  class基础{枚举状态{STATE_1,STATE_2,STATE_3};};派生类:公共基础{枚举状态{STATE_4};}; 

...我们想要派生的地方有一个枚举来描述它可能处于的状态,这些状态是:STATE_1,STATE_2,STATE_3和STATE_4.我们实际上并不想更改基类中的枚举,因为其他派生类可能没有能力进入STATE_4.我们也不想创建一个新的枚举,因为在Base中已经有一个用于State的枚举.

我们是否仍使用静态const值代替,以便在8年后完成此工作?

  class基础{static int STATE_1 = 0;静态整数STATE_2 = 1;static int STATE_3 = 2;};派生类:公共基础{static int STATE_4 = 3;}; 

解决方案

不,C ++不允许这种事情. Base :: Color 是与 Derived :: Color 完全独立的类型,与它们的连接为零.这与任何其他嵌套类型没有什么不同;在基类中定义的嵌套类型未连接到在派生类中定义的嵌套类型.

枚举也不能相互继承.

无论如何,这种事情往往与良好的OOP做法背道而驰.毕竟,如果派生类引入了新的枚举器,则基类将如何处理它?不同的派生类实例将如何处理它?<​​/p>

如果 Base 定义了对枚举的操作,则 Base 定义了对其进行操作的枚举的总数,并且从它派生的每个类都应该能够处理所有这些选项.否则,您的虚拟界面出了点问题.

I frequently come across a situation where we create a class that acts on some enumeration, but later we derive and we want to add more values to the enumeration without changing the base class.

I see this question from 2009: Base enum class inheritance

However, I know there were a number of changes to enum in C++11, 14, 17. Do any of those changes allow for extension of enums from base class to derived?

class Base 
{ 
   enum State {STATE_1, STATE_2, STATE_3}; 
};

class Derived : public Base 
{ 
   enum State {STATE_4};
}; 

...where we want derived to have an enumeration describing the states it can be in, which are: STATE_1, STATE_2, STATE_3, and STATE_4. We don't really want to change the enumeration in the base class, because other derived classes might not have the ability to be in STATE_4. We don't really want to create a new enumeration either, because we already have one for State in the Base.

Do we still use static const values instead in order to accomplish this 8 years later?

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; 
};

解决方案

No, C++ does not allow this sort of thing. Base::Color is a completely separate type from Derived::Color, with zero connection to them. This is no different from any other nested types; nested types defined in a base class are not connected to nested types defined in a derived class.

Nor can enumerations be inherited from one another.

This sort of things tends to go against good OOP practices anyway. After all, if a derived class introduces a new enumerator, how would the base class handle it? How would different derived class instances handle it?

If Base defines an operation over an enumeration, then Base defines the totality of the enumeration it operates on, and every class derived from it ought to be able to handle all of those options. Otherwise, something is very wrong with your virtual interface.

这篇关于枚举支持继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆