首页 > 解决方案 > 输出数组的值而不是数组的内存地址

问题描述

所以我在 C++ 中创建了一个基本的多项式类,它将这些多项式的系数动态地存储在堆上。我目前正在重载运算符,以便我可以一起添加/减去多项式以简化它们等。但是,当我尝试重载 * 运算符时,我得到了意想不到的结果。看起来它不是返回数组中索引的值,而是返回数组的位置。这是我的 .cpp 文件中的 *operator 方法:

Polynomial Polynomial::operator*(Polynomial p) {
int maxDegree = (degree)+(p.degree - 1);
int *intArray3 = new int[maxDegree];
int i, j;
for (int i = 0; i < degree; i++) {
    for (int j = 0; j < p.degree; j++) {
        cout << getCoef(i) << " * " << p.getCoef(j) << " = " << getCoef(i)*p.getCoef(j) << endl;
        intArray3[j] += (getCoef(i))*(p.getCoef(j));
        cout << " intArray3[" << j << "] contains : " << intArray3[j] << endl;
    }
}
return Polynomial(maxDegree, intArray3);}

这些行:

cout << getCoef(i) << " * " << p.getCoef(j) << " = " << getCoef(i)*p.getCoef(j) << endl;

cout << " intArray3[" << j << "] contains : " << intArray3[j] << endl;

返回

10 * 1 = 10
intArray3[0] contains : -842150441

在我的控制台中。我假设问题出在我在某处使用指针,但我无法终生思考为什么。我以与我的 + 和 - 重载类似的方式实现了这个重载,它们工作正常。任何帮助将不胜感激。干杯。

标签: c++arrayspolynomials

解决方案


推荐阅读