[英]Trouble properly dereferencing pointer to pointer
在概念上一直在为此苦苦挣扎,我不确定如何获得我正在寻找的预期结果。 我正在构建一个 HashMap 类,但我不确定如何克服每次尝试访问任何方法或属性时不断出现的错误。 我确实有一个类似 HashMap 类的模板,它使用向量模板而不是双指针,但我也无法成功地将它适应我在这里的使用(加上双指针在为分配提供的模板中)。 这是代码的简化片段:
#include <cstddef>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
const int TABLE_SIZE = 128;
template <typename HashedObject>
class HashMap {
public:
HashMap() {
table = new HashEntry*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = NULL;
}
enum EntryType {
ACTIVE, EMPTY, DELETED
};
void test() {
// This produces a compile error "request for member 'info' in '*((HashMap<int>*)this)->HashMap<int>::table',
// which is of pointer type 'HashMap<int>::HashEntry*' (maybe you meant to use '->' ?)"
cout << table[0].info << endl;
// But when I use ->, it just crashes at runtime.
cout << table[0]->info << endl;
}
private:
struct HashEntry
{
HashedObject element;
EntryType info;
HashEntry(const HashedObject & e = HashedObject(), EntryType i = EMPTY): element(e), info(i) {}
};
HashEntry **table;
};
int main(void){
HashMap<int> hashtable;
hashtable.test();
return 0;
}
我知道我很可能没有正确尊重 ** 表,但是我很难综合我所读到的关于指针和引用的内容并将其应用于这种情况。 任何帮助,将不胜感激。
cout << table[0].info << endl;
需要是
cout << table[0]->info << endl;
因为table[0]
是一个指针。
程序崩溃,因为table[0]
在取消引用时为 NULL。
将其更改为:
if ( table[0] != NULL )
{
cout << table[0]->info << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.