多项式代码

时间:2015-04-18 00:23:35

标签: c++ function friend istream

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

1 个答案:

答案 0 :(得分:1)

缺少代码 - 例如Polynomial对象的构造函数的实现。

我很确定您的错误是您没有为coefficients数据成员分配(足够)内存。

必须有
coefficients = new double[number_of_coeffs]

代码中的某处。

修改

您需要执行以下操作:要求(重新)设置多项式的次数。因为那时你知道多项式的次数:

在这里你必须复制传递的元素:

Polynomial( int degree, const double* coefficients ):
    coefficients( new double[degree] ), degree( degree )
{
    ::memcpy(this->coefficients, coefficients, degree * sizeof(double));
}

并且在这一个中,多项式的次数发生了变化 - 因此必须相应地修改系数数组。

Polynomial::setDegree( int degree ) {
     // first delete the old coefficients
     delete [] coeffs;
     // and make a new array
     this->degree = degree;
     this->coefficients = new double[ this->degree ];
     // initialize the coefficients
     ..
 }

必须在复制构造函数和赋值运算符中执行类似的操作。

最后:您可能最好使用std::vector<double>,这基本上可以为您完成所有内存管理。见http://en.cppreference.com/w/cpp/container/vector