2014-07-26 24 views
0

我試圖使用operator+函數將兩個對象一起添加到包含int數組。我得到不可靠的答案,我不知道爲什麼。爲什麼我的組合數組中的某些成員獲得奇怪的int值?當在對象上重載求和運算符時,無法可靠地將兩個int數組添加到一起?

下面是函數:

IntArray operator+(const IntArray& in1, const IntArray& in2){ 
    IntArray temp; 

    for (int i = in1.low(); i <= in2.high(); i++){ 
     temp.iArray[i] = in1.iArray[i] + in2.iArray[i]; 
    } 

    return temp; 
} 

,這裏是輸出我得到:

Sum of two arrays assigned to third array: IntArray a(1, 5); 
              IntArray b(4, 8); 
              IntArray c = a + b; 

a[1] = 10 a[2] = 20 a[3] = 30 a[4] = 40 a[5] = 50` 
b[4] = 40 b[5] = 50 b[6] = 60 b[7] = 70 b[8] = 80` 
Press any key to continue. 

c[0] = 0 c[1] = 32777 c[2] = 100 c[3] = 38 c[4] = 80 c[5] = 100 c[6] = 60 c[7] = 74 c[8] = 80 c[9] = 32767 
Press any key to continue. 

我缺少的東西?

編輯:添加代碼IntArray

class IntArray{ 
private: 
    int *arrPtr; 
    int iArray[SIZE]; 
    int arrLower, arrUpper; 
    int size; 
    string name; 

public: 
    IntArray(); 
    IntArray(int range); 
    IntArray(int lower, int upper); 
    IntArray(const IntArray& input); 
    int high() const; 
    int low() const; 
    int compare(int in1, int in2) const; 
    int operator==(const IntArray& in); 
    int operator!=(const IntArray& in); 
    void setName(string input); 
    IntArray& operator=(const IntArray& in); 
    int& operator[] (int size)    { return iArray[size]; } 
    IntArray& operator+=(const IntArray&); 
    friend IntArray operator+(const IntArray& in1, const IntArray& in2); 
    friend ostream& operator<<(ostream& os, const IntArray& i); 



}; 

和構造:

IntArray::IntArray(int lower, int upper){ 
    arrLower = lower; 
    arrUpper = upper; 
    // Creates array size 
    size = arrUpper - arrLower + 1; 
    operator[](size); 

} 

這裏是整個程序的鏈接:

https://gist.github.com/anonymous/fd4b8a5e1d1ac4d0982a

+1

請提供'IntArray'的代碼。 – Pradhan

+0

@Pradhan新增。我很抱歉。 – Ryan

+0

@Ryan:這還不夠。發佈成員函數定義。特別是構造函數。 – AnT

回答

0

當你的天堂」提出你的實施IntArray,從結果看來,罪魁禍首就是你的for循環。我猜你的IntArray不會初始化它的lowhigh範圍以外的值。但是,您的for循環假定索引>= in1.low()的所有值對於in2都有意義。但是,b[0]b[3]將是未初始化的垃圾。這就是爲什麼c[0]c[3]沒有意義。一個簡單的解決方案是在索引超出界限時將operator[]的實現更改爲返回適當的值(可能爲0)。

編輯:看起來像你想operator[]non-const,使它更自然。因此,您可以在operator+中恰當地處理出界情況。或者,提供一個const at函數,該函數進行範圍檢查,如果超出範圍,則返回一個虛擬值。

+0

添加了一個鏈接到整個程序,我也會仔細檢查'operator []'。謝謝 – Ryan

0

您的加法運算符會添加索引從in1.low()in2.high()的數組元素,即在您的具體示例中,這將從1到8.但您絕不會初始化任何數組的相應範圍之外的值。在每個數組中,超出範圍的值都包含垃圾。因此結果中的垃圾。

例如,in1.iArray[1]包含有意義的值。但是您從未初始化in2.iArray[1]in2.iArray[1]包含垃圾。 in1.iArray[1] + in2.iArray[1]評估結果中顯示的垃圾值並不奇怪。

對於in2.iArray[2]in2.iArray[3]也是如此。他們也包含垃圾。

您代碼中唯一有意義的添加項是in1.iArray[4] + in1.iArray[4]in1.iArray[5] + in1.iArray[5]。之後,它再次增加垃圾,這一次在in1一側:in1.iArray[6],in1.iArray[7]in1.iArray[8]包含垃圾。

0

沒有什麼奇怪的,如果你檢查下面的對齊版本,你可以很容易地推斷出結果。

  a[1] = 10  a[2] = 20 a[3] = 30 **a[4] = 40 a[5] = 50** 
                **b[4] = 40 b[5] = 50** b[6] = 60 b[7] = 70 b[8] = 80 
c[0] = 0 c[1] = 32777 c[2] = 100 c[3] = 38 **c[4] = 80 c[5] = 100** c[6] = 60 c[7] = 74 c[8] = 80 c[9] = 32767