c++ - 从静态函数访问非静态结构

标签 c++ linked-list static-methods

我正在尝试从静态函数 Initialize() 访问 HashTable,它是一个非静态成员

这就是我的代码的样子。 运行时出现以下错误

“对 `Hash::HashTable' 的 undefined reference ” 有什么方法可以让我访问来自 Initialize 的 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;
}

最佳答案

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

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

hash.cpp

关于c++ - 从静态函数访问非静态结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19666397/

相关文章:

c++ - MFC编程: error while compiling: error in code of a thread

c++ - 模板内嵌套类型名称的流运算符重载

c++ - 超时后重新发出与 Libcurl 的连接

c++ - 不确定如何将 duration_cast 用作宏函数

C 结构体和链表之争

c - 具有链接队列输出错误的 BST

c++ - 如何在 Travis CI 中使用最新的 boost 版本?

java - Java 中的链表数组

java - Java 中的静态方法和接口(interface)

python - 速度静态方法与类方法