如何处理传递给构造函数的语法有效但逻辑无效的参数?

bhu*_*hni 5 c++ error-handling class

我需要创建一个具有这样的公共接口的类Expr:

class Expr{
    //...
public:
   Expr(const char*);
   int eval();           //Evaluates the expression and gives the result
   void print();
};
Run Code Online (Sandbox Code Playgroud)

在设计中,如果用户输入无效字符串来构造Expr对象,如"123 ++ 233 + 23/45",那么最初构造Object并在对该对象调用eval()时通知错误是否正确.

或者应该在该点检查错误本身并抛出异常,但这会导致运行时严重增加.并且用户可以编写代码,并假设创建了Object,并且仅在运行时发现错误.

这样的问题总是在创建一个类时出现,是否有一种相当标准的方法来处理用户的这些错误?

Luc*_*ore 5

关于如何执行此操作的唯一标准部分是完整的文档.

我更喜欢尽早抛出错误,或者使用工厂来处理这种类型的对象 - 需要初始化特定参数的对象.如果您使用工厂,您可以退回一个NULL或一个nullptr或其他.

我没有看到构造对象的意义,只有在eval()调用时才返回错误.重点是什么?无论如何,对象无效,为什么要等到你使用它?

并抛出异常,但这会导致运行时间的严重增加.

你有没有想过这个?不要因为假设运行时间增加而使用异常.

  • "当你必须失败时,尽快吵闹失败." (2认同)
  • @bhuwansahni:为什么?必须在_some_阶段检查表达式的有效性. (2认同)

App*_*ker 5

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; 
}
Run Code Online (Sandbox Code Playgroud)

  • 当然,人们会认为`illogical_expression_exception`报告表达中导致这种诊断的位置,以及解释为什么这被认为是不合逻辑的.当然,人们会在`catch`子句中调用`e.what()`来打印该诊断. (2认同)