2013-10-29 238 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