我在多项式类中重载 *= 运算符时遇到了一些问题。我已经包含了我认为与解决以下问题相关的所有内容。对于代码的长度,我深表歉意。
以下是我认为相关的类标题部分。
#ifndef POL_H
#define POL_H
#include <string>
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
class Pol
{
// private data members
string polname; // polynomial name
int degree; // polynomial degree
int *coef; // array with polynomial coefficients
public:
// constructors
Pol(string, int, int*); // with input name, degree
// and array of coefficients
// operator overloading
Pol operator *= (Pol);
// other methods
void PrintPol ();
这是我的 .C 文件,重载了 *=。我决定不包括 PrintPol 方法,因为它很长,而且我几乎 100% 确定问题不在于它。
#include "Pol.h"
Pol::Pol (string s, int d, int *c)
{
degree = d;
polname = s;
coef = new int [degree + 1];
coef = c;
// initializes polynomial of degree d with c coefficients
// named s
}
Pol Pol::operator *= (Pol p1)
{
int *cp = this->coef; // If I print the values stored in cp at this point
// everything is alright
for (int i = p1.degree; i >= 0; --i)
{
for (int j = this->degree; j >= 0; --j)
{
this->coef[i + j] += p1.coef[i] * cp[j];
cout << cp[j] << endl; // When I print the values here, they've changed!
}
}
this->degree += p1.degree;
return *this;
}
我的第一个想法是,也许我越界了,但是我创建的数组cp的大小是this->degree,这也是“j”假设的最高值,所以我认为不可能吧。
这只是我的主要功能。我怀疑问题出在这里,但我还是将其包括在内,这样您就可以看到我是如何使用我声明的方法的。
#include "Pol.h"
#include <iostream>
using namespace std;
int main ()
{
int a [9] = {0, 0, 2, 4, 0, 0, 5, 0, 1};
int b [5] = {4, -2, 0, 0, 1};
Pol P2 ("P2", 4, b);
Pol P4 ("P4", 8, a);
P4*= P2;
P4.PrintPol();
return 0;
}
这可能真的很明显,我只是在自欺欺人,但我盯着代码看了好几个小时,还是想不通。提前致谢。
最佳答案
您问的是重载*=
,但问题与*=
无关。你说你的数组值是“自发地”改变的,但你显然是在代码中自己改变它们。
int *cp = this->coef; // "If I print the values stored in cp at this point
// everything is alright"
for (int i = p1.degree; i >= 0; --i) {
for (int j = this->degree; j >= 0; --j) {
this->coef[i + j] += p1.coef[i] * cp[j]; // <-- Well, you changed them here mate
cout << cp[j] << endl; // "When I print the values here, they've changed!"
}
}
从您评论 coef
声明的方式来看:
int *coef; // array with polynomial coefficients
您似乎认为coef
是一个数组;它不是。您似乎还认为将 coef
分配给另一个 int*
会复制它指向的基础数据;它不会。
coef
是一个指针,将它赋值给另一个指针只是复制指针。
尝试像其他人一样使用 std::vector
,以便为您管理数据所有权和生命周期,这样您就可以利用基本的赋值操作。
关于C++ - 类成员函数中的数组值自发改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26566952/