#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は同じサイズを持ち、正しく初期化されています(私は両方をチェックしました)。C++:演算子オーバーロード、演算子+
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.
問題がどこにあるかを調べるためにコメントを追加しました。私はエラーの原因を取得していない?
「p + q」行が表示されません。 –
クラスに適切なコピーコンストラクタがありますか? –
3つのルールに従っていることを確認してください。 –