是否有一种模式可以从C++中的另一个枚举继承枚举?
像这样的东西:
enum eBase
{
one=1, two, three
};
enum eDerived: public eBase
{
four=4, five, six
};
Run Code Online (Sandbox Code Playgroud)
Myk*_*yev 90
#include <iostream>
#include <ostream>
class Enum
{
public:
enum
{
One = 1,
Two,
Last
};
};
class EnumDeriv : public Enum
{
public:
enum
{
Three = Enum::Last,
Four,
Five
};
};
int main()
{
std::cout << EnumDeriv::One << std::endl;
std::cout << EnumDeriv::Four << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*ndy 62
不可能.枚举没有继承.
您可以使用具有命名const int的类.
例:
class Colors
{
public:
static const int RED = 1;
static const int GREEN = 2;
};
class RGB : public Colors
{
static const int BLUE = 10;
};
class FourColors : public Colors
{
public:
static const int ORANGE = 100;
static const int PURPLE = 101;
};
Run Code Online (Sandbox Code Playgroud)
不幸的是,在C++ 14中是不可能的.我希望我们在C++ 17中有这样的语言功能.由于您已经为您的问题找到了一些解决方法,因此我不会提供解决方案.
我想指出,措辞应该是"延伸"而不是"继承".扩展允许更多的值(在您的示例中,您从3跳到6个值),而继承意味着将更多约束放到给定的基类中,因此可能性会缩小.因此,潜在的铸造将与继承完全相反.您可以将派生类强制转换为基类,而不是反过来继承类继承.但是当有扩展时,你"应该"能够将基类强制转换为扩展而不是反之.我说"应该"因为,正如我所说,这样的语言功能仍然不存在.