具有查错、计算的表达式类(头文件)

作者在 2009-03-06 12:12:24 发布以下内容
new document

// Expression.h

////////////////////////////////////////////

 

#pragma once

 

#include <string>

 

/*

Expression类包含了与表达式有关的功能,

1.中缀转后缀

2.表达式检查

     出错处理

         错误种类

         1.非法字符    x+2

         2.括号不匹配  2+(3-9

         3.错误表达    2(   2#2   **  /)

3.表达式化简

4.表达式计算 

     出错处理 //未实现

         错误种类

         1.数据溢出    123456789012

         2.除异常

*/

 

/*

文法:

E ::= iS | (E)     //首部或(1+2)

E ::= ES      //后部+3*4

 

S ::= +E

S ::= -E

S ::= *E

S ::= /E

 

S ::= '\0'

*/

 

/*

去括号:

1+(1)+12 +2

(

1

1-(1*2)+1

*/

 

class Expression

{

public:

     struct Error

     {

         int value;

         int position;

     };

     //types of errors

     enum ErrType

     {

         //errors when analysing

         CORRECT_EXP,       //none error.

         ILLEGAL_CHAR,      //illegal character.

         UNMATCHED_BRACKET, //unmatched bracket.

         ILLEGAL_COMB,      //illegal combination.

         UNEXPECTED_END,    //unexpected end of expression.

         NONE_EXP,          //none expression exist.

         //errors when executing

         OVERFLOW,          //data overflow.

         DIV_BY_ZERO        //divided by zero.

     };

 

protected:

     //types of character

     enum CharType

     {

         OPT,     //operator

         OPD,     //operand

         ILLEGAL, //illegal character

         OPEN,    //opening bracket

         CLOSE,   //closing bracket

         EOS      //exiting string

     };

 

//----------------------------------------------------------------

 

public:

     static const char* GetErrMsg(int value);

 

//----------------------------------------------------------------

 

public:

     Expression(const std::string& exp);

     const std::string& ExpStr();                  //返回表达式

     bool Check(Error* pErr = NULL);               //语法检查

     bool Predigest();                             //简化表达式

     double   ExpValue();                          //获得表达式的值

     int      OptCmp(char left,char right);        //运算符优先级比较

     double   Calc(double left,char opt,double right);

     std::string        ToSuffix();                //获得等价后缀表达式

 

//----------------------------------------------------------------

 

protected:

     void Format(); //过滤空格

     ErrType  CheckMain(int& pos,int& bracket);    //pos游标,bracket括号(+1,)-1

     ErrType  CheckSub(int& pos,int& bracket);

     int      DataSize(int& pos);                  //获得pos开始的数字串长度

     int      IndexOpt(char opt);                  //获得运算符索引

     CharType GetType(int& pos);                   //获得pos开始的串类别

 

//----------------------------------------------------------------

 

private:

     std::string szExp;

     bool bValid;

};


 

 

 

 

算法 | 阅读 2628 次
文章评论,共0条
游客请输入验证码