2016-09-19 99 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; 
     }