如何处理传递给构造函数的语法有效但逻辑无效的参数
How to handle a syntactically valid but logically invalid argument passed to the constructor?
我需要创建一个具有公共接口的类Expr,如下所示:
class Expr{
//...
public:
Expr(const char*);
int eval(); //Evaluates the expression and gives the result
void print();
};
在设计中,如果用户输入了一个无效字符串来构造一个Expr对象,如"123++233+23/45",那么最初构造该对象并在对该对象调用eval()时通知错误是否正确。
或者应该在这一点上检查错误本身并抛出异常,尽管这会导致运行时间的严重增加。用户可以假设Object已经创建,并且只会在运行时发现错误。。
在创建类时总是会出现这样的问题,是否有一种相当标准的方法来处理用户的错误????
关于如何做到这一点的唯一标准部分是全面的文档。
我更喜欢尽早抛出错误,或者对这种类型的对象使用工厂——需要初始化特定参数的对象。如果使用工厂,则可以返回NULL
或nullptr
或其他任何值。
我不认为构造对象并仅在调用eval()
时返回错误有什么意义。有什么意义?不管怎样,这个对象是无效的,为什么要等到你使用它呢?
并抛出异常,尽管这会导致严重的增长在运行时。
你介绍过这个吗?不要因为假设运行时会增加而使用异常。
class illogical_expression_exception : public virtual exception {};
class Expr{
//...
int result; // store evaluated result.
public:
explicit Expr(const char*);
int getResult(); // Evaluate & Parse in the Constructor.
void print();
};
/* in constructor */
if ( ! checkExpression(expr) ) throw illogical_expression_exception();
/* in main() */
try{ Expr my_expr("2+2*2"); }
catch(const illogical_expression_exception& e){
cout << "Illogical Expression." << endl;
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- 欧拉项目#8答案是大以获得有效答案
- QMetaObject invokeMethod的基于函数指针的语法
- 调整大小后指向元素值的指针unordered_map有效?
- 为什么是0;C++中的有效语句
- 最高有效数字侧的第N位
- GCC对可能有效的代码抛出init list生存期警告
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 库特 << 2[ "abc" ] << endl;为什么它有效?这是哪种语法?
- 在不使用专用语法的情况下,为不同类型的不同方式实现模板类的方法是否有效C++?
- C++:有没有一种有效的方法来语法上使用指针等索引
- 如何处理传递给构造函数的语法有效但逻辑无效的参数
- 在C++中,我们如何用有效的X(Args..)语法调用执行函数的所有内容
- c++位字段(有效地传递它,也就是.语法糖)
- 提高精神气-有效引用语法
- 在c++代码中是否有任何例子表明三重冒号(:::)是有效的语法?
- 是否可以使用 WFP 发送带有有效负载的 tcp 语法数据包