Extending enum in derived classes

前端 未结 8 2353
陌清茗
陌清茗 2021-02-13 03:53

I have a class hierarchy, and each class in it has an exception class, derived in a parallel hierarchy, thus...

class Base
{
};

class Derived : public Base
{
};         


        
相关标签:
8条回答
  • 2021-02-13 04:35

    First: enums cannot be derived; you're just out of luck there.

    Second, it sounds like you're over-thinking your exception model. Rather than have every class use a custom derived exception specific to that class, build a series of exceptions that have semantic value that your classes could throw. For example, if you're throwing because a required argument was null, you might throw a NullArgumentException. If you're throwing because of a math overflow, you might throw an ArithmeticOverflowException.

    In your enum model, you're putting the semantic value on the enumeration; I suggest you put the semantic value on the type of the exception. You can catch multiple types of exceptions, remember.

    For examples of semantically valued exceptions, look into the standard C++ library or, for a more extensive list, the libraries of Java or C#.

    0 讨论(0)
  • 2021-02-13 04:36

    I would like, in the DerivedException class, to extend the enumeration type to include a new value THE_OTHER_REASON, so that the DerivedException class could hold any of the three values.

    Just assign the first value of a new enum. This works since you're just using the enum as a way of declaring constants.

    class DerivedException : public BaseException
    {
        enum {THE_OTHER_REASON = THAT_REASON + 1, THE_REALLY_OTHER_REASON, ETC};
    };
    

    The problem is that you can't really expect uniqueness of the enums between derived classes, without defining a "chain" of derived classes (i.e. one starts its enums after another's). However, if you only need uniqueness within a single branch of the exception class tree, it can work fine.

    0 讨论(0)
提交回复
热议问题