在派生类中扩展枚举 [英] Extending enum in derived classes
问题描述
我有一个类层次结构,它的每个类都有一个异常类,在并行层次结构中派生,因此...
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
{
};
class BaseException : public std::exception
{
enum {THIS_REASON, THAT_REASON};
};
class DerivedException : public BaseException
{
// er...what?
};
我想在DerivedException类中扩展枚举类型以包括一个新值THE_OTHER_REASON,所以DerivedException类可以保存这三个值中的任何一个。
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.
首先,我应该这样做吗?它似乎是一个合理的做法吗?如果是这样,我该怎么办呢?如果没有,您会推荐什么替代方案?
First of all, ought I to want to do this? Does it seem a reasonable practice? If so, how do I go about it? If not, what alternatives would you recommend?
编辑:建议可能的重复项这里,但是建议的解决方案是不同的,因为这个问题是针对C#和C ++。
A possible duplicate has been suggested here, but the suggested solutions are different because that question is for C# and this for C++.
推荐答案
从OO的角度来看,这是不合理的。因为你说 DerivedException
是-a BaseException
,其可能的原因必须是 > c> ,而不是超集。否则,您最终会违反 Liskov替换原则。
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.
此外,因为C ++枚举不是类,所以不能扩展或继承它们。您可以在 DerivedException
中的单独枚举中定义其他原因,但最终会遇到上述相同的问题:
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 ???)
...
}
$ b b
你可以做的是为每个不同的原因定义一个单独的异常子类。然后你可以处理它们多态(如果需要)。这是标准C ++库以及其他类库的方法。因此,您遵守约定,这使您的代码更容易理解。
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.
这篇关于在派生类中扩展枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!