我正在爲我的C++類工作,並且在運行程序時遇到了一些小問題。調試時出現錯誤,說明Unhandled exception at 0x000944C8 in Pog11.exe: 0xC0000005: Access violation writing location 0x00000000.
。目標是讀取多項式的int
度數以及double
係數。 這裏要說的是我提供的.h文件中:多項式代碼
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include<iostream>
using std::ostream;
using std::istream;
using std::cerr;
using std::endl;
class Polynomial
{
friend ostream& operator<<(ostream& left , const Polynomial& right);
friend istream& operator>>(istream& left , Polynomial& right);
public:
Polynomial();
Polynomial(int degree, const double* coefficients);
Polynomial(const Polynomial&);
~Polynomial();
const Polynomial& operator=(const Polynomial& deg);
bool operator==(const Polynomial& deg) const;
void setDegree(int d);
int getDegree() const;
private:
int degree;
double* coefficients;
};
#endif
而且這裏的代碼導致該錯誤的段:
istream& operator>>(istream& left, Polynomial& right)
{
int tmp;
left >> tmp;
right.setDegree(tmp);
int i = 0;
while (i<=right.getDegree())
{
double co;
left >> co;
right.coefficients[i] = co;
i++;
}
return left;
}
具體的right.coefficients[i]=co;
線是什麼原因導致程序崩潰。
下面是類構造函數:
#include "Polynomial.h"
Polynomial::Polynomial() :degree(0), coefficients(0)
{
degree = 0;
coefficients = new double[degree];
}
Polynomial::Polynomial(int deg, const double* coefficients)
{
if (deg < 0)
{
degree = 0;
}
else
{
degree = deg;
}
coefficients = new double [degree];
}
Polynomial::Polynomial(const Polynomial& deg)
{
if (deg.getDegree() <= 0)
{
setDegree(0);
}
else
{
setDegree(deg.getDegree());
for (int i = 0; i < degree; i++)
{
coefficients[i] = deg.coefficients[i];
}
}
}
請提供[MCVE](http://www.stackoverflow.com/help/mcve)。 「係數」如何初始化?問題在於未包括在問題中的代碼。 – Barry