cpp 数组 - 分配常量索引有效,而非常量索引不起作用
cpp array - Assigning constant index works while non-constant index does not work
>我正在尝试为数组赋值。
数组指针的类型是 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;
}
相关文章:
- #定义c-预处理器常量..我做错了什么
- 数组索引的值没有增加
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- cpp 数组 - 分配常量索引有效,而非常量索引不起作用
- 片段着色器中的"错误:在 GLSL 1.30 及更高版本中禁止使用非常量表达式索引的采样器数组"
- 如何消除"仅使用常量表达式索引到数组"警告?
- 从常量字符*参数中取出索引
- 属性树常量迭代器的索引
- 将常量字符串分配给大小恒定的 char 数组,在未使用的数组索引中会发生什么
- 在 Boost 的多索引容器中获取一个非常量迭代器
- 程序反馈:命名循环索引和引用常量数据
- 返回常量字符数组中字符最后出现的索引
- 我可以以非常量的方式使用 Boost.Range 索引适配器吗?
- 需要对 std::tuple 进行非常量索引访问的雄辩解决方案(即 std::get<E>)