超载操作员的麻烦

时间:2014-03-24 07:24:52

标签: c++ postfix-notation infix-notation

您好我试图创建一个程序,从文件中读取一系列中缀表达式,直到它到达分号或句点(A + B。),然后输出表达式的后缀另一个文件。我无法让我的重载运算符正常工作。谁能给我一些关于它们有什么问题的提示?

std::istream& operator>>(std::istream& in, expression& x) {
    char y;
    do {
        in >> y;
        x.ifix += y;
        if (y == '.') {
            x.last = true;
        }
    } while (y!= ';' || y!= '.');
    x.convertToPostfix();

    return in;
}

std::ostream& operator<<(std::ostream& out, const expression& x) {
    out << x.pfix;

    return out;
}

2 个答案:

答案 0 :(得分:1)

此表达式始终为真:

while (y != ';' || y != '.');

如果y';',则y不能为'.',因此下半部分为真。 y '.'while (y != ';' && y != '.'); 时相同但相反。

你想要

while (!(y == ';' || y == '.'));

或者,如果你想表达它更像人类:

{{1}}

换句话说,&#34;做y,而y不等于分号或点&#34;。

这是一个非常常见的错误,在组合条件时,值得花一些时间来理解,以便你可以在将来发现它 - 因为你会再次犯这个错误,我保证。

答案 1 :(得分:0)

class expression
{
    ...
   friend std::istream& operator>>(std::istream& in, expression& x);
   friend std::ostream& operator<<(std::ostream& out, const expression& x);
};

std::istream& operator>>(std::istream& in, expression& x) {
    char y;
    do {
        in >> y;
        x.ifix += y;
        if (y == '.') {
            x.last = true;
        }
    } while (y!= ';' && y!= '.');            // you meant && here, right?
    x.convertToPostfix();

    return in;
}

std::ostream& operator<<(std::ostream& out, const expression& x) {
    out << x.pfix;

    return out;
}