gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:45:01 24 4
gpt4 key购买 nike

我是 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 分配给数组中的索引位置时出现此错误

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

我做错了什么?

最佳答案

您正在返回对 const 的引用 - 这意味着它不可修改(根据错误消息,它是一个“只读位置”)。但是无论如何你都在尝试修改它。

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

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

为此,elt 需要固定为正确的类型:int*。毕竟,您创建的是 int 数组而不是 char 数组。


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

关于c++ - 错误 : assignment of read-only location ‘arr2.IntArray::operator[](1)’ arr2[1] = 24;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36393378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com