2

我必须编写这两种方法,以打印出其中包含的内容:

ex 是一个由 tokenType tk 组成的数组(对不起,试图节省空间并避免发布整个结构)

不幸的是,我收到一个编译错误,上面写着:error: no match for âoperator[]â in âex[i]â

我该如何解决这个问题,以便它将覆盖<<,以便第二种方法使用第一种?

ostream & operator<< ( ostream & os , const tokenType & tk)
{
    switch (tk.category)
    {
            case TKN_OPRAND:
            os << tk.operand;
            break;
            case TKN_OPRTOR:
            os << tk.symbol;
            break;              
    }
    return os;
}

ostream & operator<< ( ostream & os , const expression & ex)
{   
    tokenType tk;

    for (int i = 0; i < ex.numTokens; i++)
    {
        tk = ex[i];
        os << tk.operand << " ";  //problem line is this one
    }   
    return os;  
}

struct expression
{
    int numTokens ;
    tokenType tokens[MAX_TOKENS_IN_EXPRESSION] ;
    void print() const ;
    int  toPostfix( expression & pfx ) const ;
    int  evalPostfix( int & val ) ;
    expression() { numTokens = 0 ; } ;  // default constructor
} ;
4

2 回答 2

3

您非常接近 - 您忘记引用tokens数组,并尝试索引表达式本身。自然,编译器抱怨,因为你没有[]重载。

这应该有效:

for (int i = 0; i < ex.numTokens; i++)
{
    tk = ex.tokens[i]; // <<==== Here is the fix
    os << tk.operand << " ";
}   
于 2012-04-13T02:13:32.303 回答
1

补充详细信息后回答

您需要从 ex.tokens 实际存储,因为存在类型不匹配。您需要执行以下操作

tk = ex.tokens[i];

原始答案

这似乎不是operator<<. 相反,您的类型expression似乎没有定义operator[].

要了解如何重载operator[],请查看Overloading subscripting

于 2012-04-13T02:09:16.910 回答