gpt4 book ai didi

c++ - 多项式++ : How to increment p(x) by 1

转载 作者:行者123 更新时间:2023-11-30 04:15:35 27 4
gpt4 key购买 nike

我有一个 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( ...一些 vector ... );

cout << p++;

最佳答案

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

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);

关于c++ - 多项式++ : How to increment p(x) by 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18217687/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com