我想实现一个哈希表示例.所以为了这个目标,我创建了一个头文件,一个hash.cpp和main.cpp文件.在我的hash.cpp中,我试图运行一个虚拟哈希函数,该函数获取键值并转换为索引值.但是,每当我尝试根据该哈希类创建对象时,它会抛出一个错误(对'hash'的引用是不明确的).
这是我的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;
}
Run Code Online (Sandbox Code Playgroud)
这是我的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;
}
Run Code Online (Sandbox Code Playgroud)
这是我的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__) */
Run Code Online (Sandbox Code Playgroud)
您的hash类符号与std :: hash冲突
快速修复可能是使用全局命名空间限定符
int main(int argc, const char * argv[]) {
::hash hash_object;
Run Code Online (Sandbox Code Playgroud)
但更好的建议是停止用你的全局命名空间污染
using namespace std;
Run Code Online (Sandbox Code Playgroud)
只需使用std::cout或std::endl何时需要它们.您还可以在编写库时创建自己的命名空间.
此外,你在这里有一些大写字母拼写错误:
index = hash_object.hash("patrickkluivert");
^ I suppose you're referring to the Hash() function here
Run Code Online (Sandbox Code Playgroud)
和这里
int Hash(std::string key) {
^ this needs to be capital as well
int hash = 0;
Run Code Online (Sandbox Code Playgroud)
如果您想匹配您的声明并避免转换/链接错误.