Enums support for inheritance

跟風遠走 提交于 2020-12-31 06:09:34

问题


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

回答1:


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.




回答2:


Why not just using namespaces to group enums?

namespace my_codes {
   enum class color { red, green, blue } ;
   enum class origin { server, client } ;
} // my_codes

Usage might be

struct my_signal {
     my_codes::color  flag ;
     my_codes::origin  source ;
} ;

But beware: "overkill is my biggest fear..." :) I would not enjoy some deep hierarchy of namespaces with enums in them and a such ...



来源:https://stackoverflow.com/questions/42913431/enums-support-for-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!