0

我有一个算法试图调用一个优先级函数,以便比较一个运算符是否比另一个运算符具有更高的优先级。我有一个错误说我无法将类型 Token 转换为 char,我想知道我将如何去做。

enter code here
int precedence(char op)
{
if (op == '*' || op == '/') return 0;
return 1;
}

bool comparePrecedence(char a, char b)
{
return precedence(a) < precedence(b);
}

double eval_infix_expr(vector<Token> ie, map<string,double> sym_tab)
{

vector<Token> postfix_expr;
vector<Token> tok_list;
vector<Token> t1;
stack <Token> stack;

while(!(ie.empty())){

    for(size_t i = 0; i < ie.size() ; i++){
            Token tok = ie[i];

    if(!(tok.type == OPERATOR)){
            postfix_expr.push_back(tok);
    }else if(tok.type == OPERATOR){
            while(precedence(tok)){}

        }
    }
}
4

2 回答 2

0

In this line : while(precedence(tok)){}, you're calling the function precedence which take in argument a char but you're passing the variable tok which is a Token

The two types cannot be converted.

My crystal ball says that with while(precedence(tok.type)){}, the program may compile but this line makes no sense ! At best, it's useless, at worst, it's an infinite loop.

于 2013-09-23T18:45:53.737 回答
0

你可以通过几种不同的方式来做到这一点:

显式转换运算符

在 classToken中,您需要定义一个强制转换运算符:

class Token
{
public:
    // rest of declaration

    operator char() { return type; } // return whatever char value makes sense
};

然后,当您调用 时while (precedence(tok)) {},它将能够隐式转换它。

或者,

存取器

您可以声明一个访问器并实际使用该访问器,而不是依赖于强制转换:

class Token
{
public:
    // rest of declaration

    char GetType() const { return type; } // or whatever makes sense for your token class
};

然后当你打电话时while (precedence(tok.GetType())) {}(注意访问权限的不同),它就会知道你在做什么。

边注:

以下代码块并不是真正必要的:

if(!(tok.type == OPERATOR)) // if Not operator
{
    postfix_expr.push_back(tok);
}
else if(tok.type == OPERATOR) // else if operator
{
    while(precedence(tok)){}
}

避免潜在的无限循环,条件可以写成

if (tok.type == OPERATOR) // if operator
{
    while(precedence(tok)){} // NOTE:  This will either be a noop, or an infinite loop ... never anything useful!
}
else // otherwise
{
    postfix_expr.push_back(tok);
}

使其更具可读性。

于 2013-09-23T19:06:16.770 回答