我是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;
我做错了什么?
答案 0 :(得分:1)
您返回对const的引用 - 这意味着它不可修改(它是&#34;只读位置&#34;根据错误消息)。但是,无论如何你都试图修改它。
你打算做的是返回对非const的引用:
int& operator[] (int i) {
// same as before
}
要使其正常工作,需要修复elt
以获得正确的类型:int*
。毕竟,您制作的int
数组不是char
的数组。
注意:打印错误超出界限并不是很有帮助。您应该更喜欢抛出异常或者只是声明给定的索引是在边界内。