我正在尝试使用下标运算符创建从 1 开始索引的自定义数组。获取值工作正常,但我不知道为什么使用下标运算符分配不起作用。
class CEntry {
public:
CKey key;
CValue val;
CEntry(const CKey& key, const CValue& val) {
this->key = key;
this->val = val;
}
CEntry& operator= (const CEntry& b) {
*this = b;
return *this;
};
};
...
class EntriesArray {
public:
CEntry **entries;
int length;
EntriesArray(int length) {
this->length = length;
entries = new CEntry*[length];
int i;
for (i = 0; i < length + 1; i++) {
entries[i] = NULL;
}
};
CEntry& operator[] (const int index) {
if (index < 1 || index > length) {
throw ArrayOutOfBounds();
}
return *entries[index - 1];
};
};
以这种方式构造数组
EntriesArray a(5);
这有效
a.entries[0] = new CEntry(CKey(1), CValue(1));
cout << a[1].val.value << endl;
这不起作用
a[1] = new CEntry(CKey(1), CValue(1));
编辑:
使用
CEntry *operator=( CEntry *orig)
它编译好,但gdb停在
No memory available to program now: unsafe to call malloc warning: Unable to restore previously selected frame
带回溯
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00007fff5f3ffff8
0x00000001000013c8 in CEntry::operator= (this=0x0, orig=0x1001008d0) at /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp:20
20 /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp: No such file or directory.
in /Users/seal/Desktop/efa du2_pokus2/efa du2_pokus2/main.cpp