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

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

我是 c++ 的初学者,正在学习使用重载操作。在我的主程序中,我有这段代码:

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

在我的header中,我有这个代码

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 */
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;

我做错了什么?

您正在 return 引用 const - 这意味着它不可修改(根据错误消息,它是 "read-only location")。但是无论如何你都在尝试修改它。

你的意思是return对非常量的引用:

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

为此,elt 需要修正为正确的类型:int*。毕竟,您正在制作 int 的数组而不是 char 的数组。


注意:输出越界错误不是很有用。您应该更喜欢抛出异常或简单地断言给定的索引在范围内。