2016-09-19 125 views
-2

在概念上一直在掙扎着,我不確定如何獲得我期待的結果。我正在構建一個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; 
} 

我明白,我最有可能無法正確尊重的**表,但我有一個很難合成我讀過關於指針和引用將其應用於這種情況。任何幫助,將不勝感激。

+1

'表[0] .info'必須'表[0] - > info'因爲'表[0]'是一個指針。 –

+1

如果這是您遇到的唯一問題,則可以關閉「帖子」錯誤。 –

+0

我的問題是它似乎崩潰時,我使用表[0] - >信息。 – Brendan

回答

0
 cout << table[0].info << endl; 

需要是

 cout << table[0]->info << endl; 

因爲table[0]是一個指針。

程序崩潰,因爲table[0]在解除引用時爲空。

它更改爲:

 if (table[0] != NULL) 
     { 
      cout << table[0]->info << endl; 
     }