C++异常处理和枚举作用域
C++ Exception Handling and Enum Scoping
我编写了以下异常类:
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;
}
}
}
当来自不同枚举但相同整数值的两个值出现在同一个switchcase语句中时,我遇到了问题。当这种情况发生时,就像上面的例子一样,编译器会打印一个"错误:重复的大小写值"。我想这个错误的原因是归因于这两个家族的整数性质。我该如何解决这个问题?我是否必须将这个"通用异常方案"更改为多态方案(单个错误类型的一个异常类)?
您可以:
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
中定义的enum(因为不同的枚举器可能会成为更改后的最后一个枚举器)。
相关文章:
- 将作用域枚举转换为基础类型
- 无法让"std::enable_if"适用于无作用域枚举
- 为什么不能直接引用作用域枚举类成员,而不能为无作用域枚举生成类成员?
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 作用域枚举和标准::get
- 如何确保 Visual C++ 不允许作用域枚举访问?
- C++/错误:表达式必须具有整数或无作用域枚举类型
- C++ 在方程中使用变量;错误:表达式必须具有整数或无作用域枚举类型及其他
- 防止作用域枚举可复制/可移动
- 错误:以增量方式填充向量时,表达式必须具有整数或无作用域枚举类型
- 无作用域枚举的基础类型?
- 有效的双向作用域枚举映射
- 错误:数组大小表达式必须具有整型或无作用域枚举类型,而不是'double'
- 为什么作用域枚举默认支持运算符'<'?
- 无作用域枚举、枚举器和基础类型C++中的歧义
- 为什么要编译无作用域枚举的声明?
- 具有作用域枚举的位集无法编译
- 如何重载作用域枚举的运算符>?
- 无作用域枚举是否仍然有用
- 表达式必须具有整数或无作用域枚举类型,并带有字符串向量