从静态函数访问非静态结构

时间:2013-10-29 18:30:49

标签: c++ linked-list static-methods

我正在尝试从静态函数Initialize()

访问HashTable,它是一个非静态成员

这就是我的代码的样子。 我运行此

时出现以下错误

“对Hash :: HashTable'的未定义引用”   我可以使用与HashTable相同的定义从Initialize访问。


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;
}

1 个答案:

答案 0 :(得分:2)

这是链接器而不是编译器报告的错误。您忘记在代码中提供HashTable的定义。要修复,请添加

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

hash.cpp