【发布时间】:2011-05-09 10:28:49
【问题描述】:
我是一名 Java 程序员,但现在我必须用 c++ 编写一点代码。几年前我学习了 C++ 的基础知识,所以我不太适合。
我写了一个描述多项式的小类。这里是:
#include "Polynom.h"
#include <iostream>
using namespace std;
Polynom::Polynom()
{
this->degree = 0;
this->coeff = new int[0];
}
Polynom::Polynom(int degree)
{
this->degree = degree;
this->coeff = new int[degree + 1];
}
Polynom::~Polynom()
{
delete coeff;
}
void Polynom::setDegree(int degree)
{
this->degree = degree;
}
void Polynom::setCoeffs(int* coeff)
{
this->coeff = &*coeff;
}
void Polynom::print()
{
int i;
for(i = degree; i >= 0; i --)
{
cout<<this->coeff[i];
if(i != 0)
cout<<"x^"<<i;
if(i > 0)
{
if(coeff[i - 1] < 0)
cout<<" - ";
else
cout<<" + ";
}
}
}
好的,现在我尝试读取多项式的次数和系数并将其打印到控制台中。这是代码:
#include <iostream>
#include "Polynom.h"
using namespace std;
int main()
{
int degree;
cout<<"degree = ";
cin>>degree;
int* coeff = new int[degree];
int i;
for(i = 0; i <= degree; i++)
{
cout<<"coeff[x^"<<i<<"] = ";
cin>>coeff[i];
}
Polynom *poly = new Polynom(degree);
//poly->setDegree(degree);
poly->setCoeffs(coeff);
cout<<"The input polynome is: ";
poly->print();
return 0;
}
编译代码时,一切正常。运行时,如果我给一个even度,然后给一些系数,程序运行正常。 但是:如果我定义一个奇度(例如3或5)然后给出系数,程序不会打印多项式并返回以下错误:
malloc.c:3096: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed.
为什么会这样?我在哪里没有为数组分配足够的内存?我搜索了这个错误并偶然发现了this page,但那里提到的解决方案对我没有多大帮助。
也许您可以在我的代码中看到另一个问题?非常感谢您的帮助。
提前致谢。
【问题讨论】:
-
可以发一下头文件吗?
-
你应该在析构函数中做
delete[] coeff;或者更好的是,使用std::vector<int>(这也会让您摆脱degree成员)。 -
@Downvoter - 为什么?格式良好的问题,大量信息,海报做出了诚实的尝试。