2015-11-27 63 views
-1

我需要一些幫助來解決我遇到的錯誤。無法將指針指定給另一個指針

Error- C2440- 'initializing':cannot convert from 'DATAHash<ItemType>' to 'DATAHash<ItemType> *' 

我正在使用Visual Studio。

template<typename ItemType> 
class Hash 
{ 
private: 
    int tablesize; 
    /// Creating a Hashtable of pointer of the (class of data type) 
    DATAHash<ItemType>*  Hashtable; 

和散列類,我的默認構造函數是

template<typename ItemType> 
Hash<ItemType> ::Hash(int size) 
{ 
    tablesize = size; 
    Hashtable[size]; // make array of item type 

    for (int i = 0; i< size; i++) 
     Hashtable[i] = NULL; 

    loadfactor = 0; 
} 

這是我的錯誤是

/// This is add function 
/// It adds the data that is passed as a parameter 
/// into the Hash table 
template<typename ItemType> 
void Hash<ItemType>::additem(ItemType data) 
{ 
    DATAHash<ItemType> * newdata = new DATAHash<ItemType>(data); 

    /// gets the data as a parameter and calls Hash function to create an address 
    int index = Hashfunction(data->getCrn()); 

    /// Checking if there if there is already a data in that index or no. 
    DATAHash<ItemType> * tempptr = Hashtable[index]; <------- Error line 

    // there is something at that index 
    // update the pointer on the item that is at that index 
    if (tempptr != nullptr) 
    { 

     // walk to the end of the list and put insert it there 

     DATAHash<ItemType> * current = tempptr; 
     while (current->next != nullptr) 
      current = current->next; 

     current->next = newdata; 

     cout << "collision index: " << index << "\n"; 

     return; 
    } 

這是我第一次發佈提問所以,如果有別的東西我需要發帖,讓我知道。

感謝您的幫助。

-Rez

+0

你說,「*無法分配指針到另一個指針*「,但錯誤信息清楚地表明您正試圖爲指針變量指定一個非指針。你甚至可以評論「* make數組的類型*」,表明它確實是一個項目類型數組,而不是一個指針數組。 – user2079303

+0

'Hashtable [size]; //使項目類型的數組'沒有 –

回答

2

你需要得到的指針是這樣的:

DATAHash<ItemType> * tempptr = &Hashtable[index]; 

但是我真的不知道這是你應該做的事情。您正在調用該指針上的[]運算符,但不會爲其分配任何內存。

Hashtable成員如何初始化?

0

所以,當你像Hashtable[index]那樣得到一個東西的索引時,你會得到一個實際值。 DATAHash<ItemType>*是指針類型,因此它包含一個地址。

我猜你會尋找,走的是Hashtable[index]地址的解決方案,所以你需要修復與該行:

DATAHash<ItemType> * tempptr = &Hashtable[index];