2013-10-29 236 views
0

我試圖訪問Hashtable將是一個靜態函數初始化()訪問從靜態函數

這是我的代碼看起來像一個非靜態成員的非靜態結構。 我收到以下錯誤,當我運行這個

「未定義參考`哈希::哈希表'」 有什麼辦法,我可以訪問來自初始化與哈希表中的定義相同。


class Hash 
{ 

private: 
    static const int tableSize = 10; 
    struct item 
    { 
     string name; 
     item* next; 
    }; 
    static item* HashTable[tableSize]; 
public: 
    static void Initialize(); 
    static int Hash(string key); 

}; 
---------------------------------------------------------------------------- 



--------------------------------hash.cpp------------------------------------ 

#include<iostream> 
#include<string> 
#include "hash.hpp" 

using namespace std; 


hash::Initialize() 
{ 
     for(int i=0;i<tableSize;i++) 
     { 
      HashTable[i] = new item; //Gives an error 
      HashTable[i]->name = "empty";//Gives an error 
      HashTable[i]->next = NULL; 
     } 
} 

int hash::Hash(string key) 
{ 
    int hash=0; 
    int index=0; 
    for(int i=0;i<key.length();i++) 
    { 
      hash = (hash + (int)key[i]); 
    } 
    index = hash % tableSize; 
    cout<<"Index-"<<index<<endl; 
    return index; 

} 



int main(int argc,char** argv) 
{ 
    Hash:Initialize(); 
    Hash::PrintTable(); 
    return 0; 
} 

+0

查找一個定義規則是什麼。靜態成員需要在一個翻譯單元中實例化。簡單地包括頭文件是聲明,而不是實例化。 – yngccc

回答

2

這是從連接器,而不是編譯器報告錯誤。您忘記在您的代碼中提供HashTable的定義。要修復,添加

hash::item* hash::HashTable[hash::tableSize]; 

hash.cpp

+0

什麼?那應該已經被'#include「hash.hpp」'語句自動包含了,否? – abiessu

+0

@abiessu **否**閱讀您的C++基礎知識。靜態數據成員必須在某處被定義。類定義僅*聲明*它們。 – Walter

+0

@Walter:我的錯誤。我已經使用了一個靜態成員變量已經有一段時間了...... – abiessu