cpp 数组 - 分配常量索引有效,而非常量索引不起作用

cpp array - Assigning constant index works while non-constant index does not work

本文关键字:常量 索引 非常 不起作用 有效 分配 数组 cpp      更新时间:2023-10-16

>我正在尝试为数组赋值。

数组指针的类型是 int*。下面的代码是最小的可重现代码。

#include <iostream>
using namespace std;
class ExtendableArray;
class ElementRef {
private:
ExtendableArray *intArrayRef; //pointer to the array
int index;                    // index of this element
public:
ElementRef(ExtendableArray &theArray, int i);
ElementRef &operator=(int val);
operator int() const;
};
class ExtendableArray {
private:
int *arrayPointer; // integer array pointer
int size;          // the size of array
public:
ExtendableArray();
ElementRef operator[](int i);
friend class ElementRef;
};
int main() {
ExtendableArray arr;
printf("arr[1]: %dn", (int) arr[1]);
arr[0] = 5;
return 0;
}

ElementRef::ElementRef(ExtendableArray &theArray, int i) {
ExtendableArray *ref = &theArray;
intArrayRef = ref;
index = i;
}
ElementRef &ElementRef::operator=(int val) {
printf("0: %dn", intArrayRef->arrayPointer[0]);
intArrayRef->arrayPointer[0] = 5;
printf("0: %dn", intArrayRef->arrayPointer[0]);
printf("INDEX: %dn", index);

intArrayRef->arrayPointer[index] = 5;
}

ElementRef::operator int() const {
return this->intArrayRef->arrayPointer[this->index];
}

ExtendableArray::ExtendableArray() {
this->arrayPointer = new int[2]{0};
this->size = 2;
}
ElementRef ExtendableArray::operator[](int i) {
ElementRef ref = ElementRef(*this, i);
return ref;
}

上面的代码崩溃了

0: 0

0: 5

索引: 0

进程已完成,退出代码为 4

当我附加调试器时,调试器点intArrayRef->arrayPointer[index] = 5;

怎么会这样?我的意思是,为什么常量索引在非常量索引崩溃时起作用?

这就是 c++ 中数组的工作方式,它们有一个常量索引。你将不得不使用另一个类来解决你的问题,我建议

std::vectory<Type T>

这将允许您添加元素,存储它们,并且与c ++ Lists相比,向量的元素可以通过索引进行寻址,这感觉更像是一个长度可变的数组。

有关向量的文档可以在此处找到。

我忘记了返回语句,它会导致崩溃。当我更改代码以返回*this时,它可以工作。

编译器显示警告,但是当我按下CLion上的调试按钮时看不到警告

ElementRef &ElementRef::operator=(int val) {
printf("0: %dn", intArrayRef->arrayPointer[0]);
intArrayRef->arrayPointer[0] = 5;
printf("0: %dn", intArrayRef->arrayPointer[0]);
printf("INDEX: %dn", index);

intArrayRef->arrayPointer[index] = 5;
return *this;
}