[英]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.