2016-04-04 17 views
0

我在C++初學者誰是學習使用重載的操作。在我的主要節目,我有這樣的代碼:錯誤:只讀位置「arr2.IntArray ::操作符[](1)」 ARR2 [1] = 24的分配;

IntArray arr2(3) 
arr2[1] = 24; 

在我的頭,我有這樣的代碼

class IntArray { 
    char *elt; 
    int size 
public: 
    const int& operator[] (int i); 

在我的.cpp,我有這樣的構造:

/* one-integer constructor */ 
IntArray::IntArray(int sz) { 
    elt = new char[sz]; 
    for (int i = 0; i<sz; i++) 
    elt[i] = 0; 
    size = sz; 
} 

這index operator

/* Index operator */ 
const int& IntArray::operator[] (int i) { 
    if (i < 0) { 
    cout << "warning: value out of bounds" <<endl; 
    return elt[0]; 
    } 
    else if (i > size) { 
    cout << "warning: value out of bounds" <<endl; 
    return elt[size]; 
    } 
    else 
    return elt[i]; 
    } 

我得到這個錯誤或者當我嘗試將值24分配到陣列中的索引位置時

error: assignment of read-only location ‘arr2.IntArray::operator’ arr2[1] = 24;

我在做什麼錯?

回答

1

您返回常量的引用 - 這意味着它的不可修改的(這是一個「只讀位置」按照錯誤消息)。但是,你仍然試圖修改它。

你的意思做的是一個參考返回非const:

int& operator[] (int i) { 
    // same as before 
} 

對於這項工作,被固定elt需要有正確的類型:int*。畢竟,你正在做的int數組不是的char秒的陣列。


注意:打印出界錯誤不是很有幫助。你應該更喜歡拋出一個異常,或者只是斷言給定的索引是在邊界內。

+0

肯定的,但後來我得到這個錯誤:錯誤:從類型「詮釋」 回報ELT [0]的右值的類型「詮釋與」非const引用無效的初始化; – flowpoint

+0

@flowpoint什麼是'elt'?請添加到問題。 – Barry

+0

看到更新後 – flowpoint

相關問題