【问题标题】:C++ Exception Handling and Enum ScopingC++ 异常处理和枚举范围
【发布时间】:2015-04-10 12:52:54
【问题描述】:

我写了以下异常类:

class generic_exception : public std::exception
{

  public:

    generic_exception( std::string where, int err_code , bool fatal ) 
    : where_(where) , errcode_(err_code) ,fatal_(fatal) {}

      inline int get_errcode()
      {
        return errcode_;
      }

      inline bool is_fatal()
      {
        return (fatal_ == true ? true : false);
      }

      inline std::string get_where()
      {
        return where_;
      }

     ~generic_exception() throw () { }

  private:

    std::string where_;
    int errcode_;
    bool fatal_;

};

我用它来处理错误,而不为每种类型的错误创建一个异常类。所有 err_code 值本质上都是枚举值(所有在需要错误检查的单个类中定义的值)用作错误代码。

一些示例类:

class A
{
  enum one{a,b,c}
};

class B
{
  enum two{d,e,f}
};

尝试捕获示例:

try
    {
      //something
      throw generic_exception("where" , one::a , true );
      throw generic_exception("where" , two::a , true );

    }
    catch( generic_exception e)
    {
      switch(e.get_errcode())
      {
        case one::a:
          break;
        case two::b:
          break;
      }
    }
  }

当来自不同枚举但相同整数值的两个值出现在同一个 switch case 语句中时,我遇到了问题。 当这种情况发生时,就像上面的例子一样,编译器会打印一个“错误:重复的大小写值”。我猜这个错误的原因是 归因于两个家庭的整数“性质”。 我怎么解决这个问题?我是否有义务将这种“通用异常方案”更改为多态方案(单一错误类型的一个异常类)?

【问题讨论】:

  • 如果这些错误代码必须是唯一的,您将不得不对这些错误代码使用一个枚举,否则您将不得不做的伎俩,即第二个枚举从您的第一个枚举的最后一个值开始增加1.

标签: c++ exception exception-handling enums enumeration


【解决方案1】:

你可以:

1)使用全局枚举:

enum ErrorCode
{
    A_one,
    A_two,
    A_three,
    //...

    B_one,
    B_two,
    //...
};

2) 或者使用枚举器计数:

class A
{
public:
    enum
    {
        Err_one,
        Err_two,
        Err_three,
        //...

        Last_error
    };
};

class B
{
public:
    enum
    {
        Err_one = A::Last_error,
        Err_two,
        Err_three,
        //...

        Last_error
    };
};

Last_error 的技巧很好,因为您可以通过这种方式定义许多枚举,并且如果您添加/删除一些枚举器,它们都不需要更新。如果你想避免定义额外的枚举器,你应该分配给前一个枚举中最后一个枚举器的第一个枚举器值,增加 1。

但请注意,在这种情况下,即使A 中定义的枚举发生很小的变化,也可能需要更新B 类中定义的枚举(因为不同的枚举数可以成为更改后的最后一个)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    相关资源
    最近更新 更多