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;
我在做什麼錯?
肯定的,但後來我得到這個錯誤:錯誤:從類型「詮釋」 回報ELT [0]的右值的類型「詮釋與」非const引用無效的初始化; – flowpoint
@flowpoint什麼是'elt'?請添加到問題。 – Barry
看到更新後 – flowpoint