错误:只读位置的分配'arr2.IntArray :: operator [](1)'arr2 [1] = 24;

时间:2016-04-04 01:35:19

标签: c++ oop operator-overloading

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

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 */
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分配给数组

中的索引位置时,出现此错误
  

错误:分配只读位置'arr2.IntArray :: operator'   arr2 [1] = 24;

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您返回对const的引用 - 这意味着它不可修改(它是&#34;只读位置&#34;根据错误消息)。但是,无论如何你都试图修改它。

你打算做的是返回对非const的引用:

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

要使其正常工作,需要修复elt以获得正确的类型:int*。毕竟,您制作的int数组不是char的数组。

注意:打印错误超出界限并不是很有帮助。您应该更喜欢抛出异常或者只是声明给定的索引是在边界内。