我想实现一个哈希表示例。 为此,我创建了一个头文件、一个 hash.cpp 和 main.cpp 文件。 在我的 hash.cpp 中,我尝试运行一个虚拟哈希函数,该函数采用键值并将其转换为索引值。但是,每当我尝试根据该哈希类创建对象时,它都会引发错误(对“哈希”的引用不明确)。
这是我的 main.cpp:
#include "hash.h"
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdio.h>
using namespace std;
int main(int argc, const char * argv[]) {
hash hash_object;
int index;
index=hash_object.hash("patrickkluivert");
cout<<"index="<<index<<endl;
return 0;
}
这是我的 hash.cpp:
#include "hash.h"
#include <iostream>
#include <cstdlib>
#include <string>
#include <stdio.h>
using namespace std;
int hash(string key){
int hash=0;
int index;
index=key.length();
return index;
}
这是我的hash.h
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
#ifndef __hashtable__hash__
#define __hashtable__hash__
class hash
{
public:
int Hash(string key);
};
#endif /* defined(__hashtable__hash__) */
最佳答案
您的 hash
类符号与 std::hash 冲突
快速修复可能是使用全局命名空间限定符
int main(int argc, const char * argv[]) {
::hash hash_object;
但更好的和推荐方法是停止用
污染您的全局命名空间using namespace std;
并在需要时使用 std::cout
或 std::endl
。
如果您正在编写库,您还可以创建自己的命名空间。
此外,你这里有一些大写字母拼写错误:
index = hash_object.hash("patrickkluivert");
^ I suppose you're referring to the Hash() function here
这里
int Hash(std::string key) {
^ this needs to be capital as well
int hash = 0;
如果您想匹配您的声明并避免转换/链接错误。
关于c++ - 对 "class"的引用不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33053192/