#include<iostream>
#include"polynom.h"
using namespace std;
// operator= works !!!
int main()
{
Polynomial p(5), q(5), r(5);
cout<<"1"<<endl;
cin>>x;
p[0] = 1;
p[1] = 2;
p[2] = 3;
q[0] = 4;
q[1] = 5;
q[2] = 6;
cout<<p+q;
return 0;
}
Polynomial::Polynomial(const Polynomial ©Constructor) : size(copyConstructor.size)
{
coeffs = new double(size);
int i=0;
while(i<size)
{
coeffs[i] = copyConstructor.coeffs[i];
i++;
}
}
Polynomial::Polynomial(int s)
{
size = s;
coeffs = new double [s];
// Setting all coefficients in the polynomial equal to 0
for(int i=0; i<size; i++)
coeffs[i]=0;
}
Polynomial Polynomial::operator+ (const Polynomial &rightPoly) const
{
int BigSize, SmallSize;
Polynomial *newPoly = NULL;
cout<<"in the operator\n";
if(size == rightPoly.size)
{
cout<<"first if\n";
newPoly = new Polynomial(size);
cout<<"first if resize\n";
for(int i=0; i<newPoly->size; i++)
cout<<newPoly->coeffs[i]<<endl;
cout<<"size = "<<size<<endl;
cout<<"rightPoly.size = "<<rightPoly.size<<endl;
cout<<"newPoly->size = "<<newPoly->size<<endl;
cout<<"first if loop\n";
for(int i=0; i<size; i++)
{
cout<<"i= "<<i;
newPoly->coeffs[i] = rightPoly.coeffs[i]+coeffs[i];
cout<<" newPoly[]"<<newPoly->coeffs[i]<<endl;
}
cout<<"out of loop\n"<<endl;
}
else if(size > rightPoly.size)
{
cout<<"second if\n";
BigSize = size;
SmallSize = rightPoly.size;
newPoly = new Polynomial(BigSize);
cout<<"second if loop\n";
for(int i=0; i<SmallSize; i++)
newPoly->coeffs[i] = rightPoly.coeffs[i] + coeffs[i];
for(int i=SmallSize; i<BigSize; i++)
newPoly->coeffs[i] = coeffs[i];
cout<<"second if loop end\n";
}
else
{
cout<<"third if\n";
BigSize = rightPoly.size;
SmallSize = size;
newPoly = new Polynomial(BigSize);
for(int i=0; i<SmallSize; i++)
newPoly->coeffs[i] = coeffs[i] + rightPoly.coeffs[i];
for(int i=SmallSize; i<BigSize; i++)
newPoly->coeffs[i] = rightPoly.coeffs[i];
}
cout<<"before return\n";
return *newPoly;
}
问题:Visual Studio 2010 执行 p+q 行时,出现以下错误。p 和 q 具有相同的大小并且它们已正确初始化(我检查了它们)。
Windows has triggered a breakpoint in CNG242.exe.
This may be due to a corruption of the heap, which indicates a bug in CNG242.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while CNG242.exe has focus.
The output window may have more diagnostic information.
我添加了评论以遵循这些路线并找出问题所在。我没有得到导致错误的原因?