2015-04-18 24 views
1

我正在爲我的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]; 
    } 
} 
} 
+0

請提供[MCVE](http://www.stackoverflow.com/help/mcve)。 「係數」如何初始化?問題在於未包括在問題中的代碼。 – Barry

回答

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

+0

感謝您的回覆!你會在哪裏推薦這條新路線?我在編碼方面還是比較新的,但我仍然試圖讓所有的東西都變得清晰。謝謝 – drade13