我正在为我的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