1

我有一个Polynomial类,我正在尝试定义operator++前增量和后增量,以及尝试定义减量前和后减量,即operator--。这是我的代码片段:

class Polynomial
{
public:
    Polynomial();
    Polynomial(vector<int>coeffs);
    /*
    .
    .
    .
    */
    Polynomial operator++();
    Polynomial& operator++ (int unused);
    Polynomial operator--();
    Polynomial& operator-- (int unused);
    /*
    .
    .
    .
    */

private:
    vector<int> coefficient;
};

Polynomial Polynomial::operator++()
{
    coefficient[0]++;
    return *this;
}
Polynomial& Polynomial::operator++ (int unused)
{
    Polynomial copy(*this);
    coefficient[0]++;
    return copy;
}
Polynomial Polynomial::operator--()
{
    coefficient[0]--;
    return *this;
}
Polynomial& Polynomial::operator-- (int unused)
{
    Polynomial copy(*this);
    coefficient[0]--;
    return copy;
}

尝试在 main 中执行此类操作时出现错误:

Polynomial p(...一些矢量...);

cout << p++;

4

1 回答 1

2

您正在从后缀运算符返回对临时对象的引用:

Polynomial& Polynomial::operator++ (int unused)
{
    Polynomial copy(*this);
    coefficient[0]++;
    return copy;     // returning reference to local variable
}

这是未定义的行为。您有 post 的返回类型并以错误的方式预递增。你需要这样的东西:

Polynomial& operator++();
Polynomial operator++ (int);
Polynomial& operator--();
Polynomial operator-- (int);
于 2013-08-13T19:39:42.607 回答