Extending enum in derived classes

前端 未结 8 2379
陌清茗
陌清茗 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:14

    From the OO standpoint, it is not reasonable. Since you say that DerivedException is-a BaseException, its possible reasons must be a subset of that of BaseException, not a superset. Otherwise you ultimately break the Liskov Substitution Principle.

    Moreover, since C++ enums are not classes, you can't extend or inherit them. You can define additional reasons in a separate enum within DerivedException, but then ultimately you bump into the same problem described above:

    class DerivedException : public BaseException
    {
      enum {
        SOME_OTHER_REASON = THAT_REASON + 256, // allow extensions in the base enum
        AND_ANOTHER_REASON
      };
      ...
    };
    
    ...
    try {
      ...
    } catch (BaseException& ex) {
      if (ex.getReason() == BaseException::THIS_REASON)
        ...
      else if (ex.getReason() == BaseException::THAT_REASON)
        ...
      else if (ex.getReason() == ??? what to test for here ???)
        ...
    }
    

    What you can do instead is define a separate exception subclass for each distinct reason. Then you can handle them polymorphically (if needed). This is the approach of the standard C++ library as well as other class libraries. Thus you adhere to the conventions, which makes your code easier to understand.

提交回复
热议问题