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