【发布时间】:2014-11-15 13:41:23
【问题描述】:
我目前正在尝试为 HashMap 类实现哈希函数。我们得到了一个 HashMap.h 文件,我们不能更改任何预定义的成员变量和函数。在为 HashMap 类实现我的 .cpp 文件时,这并没有被证明是一个挑战,直到我到达这一行:
typedef std::function<unsigned int(const std::string&)> HashFunction;
通常如果这是在我的头文件中:
HashMap();
我可以在我的源文件中这样做来实现它:
HashMap::HashMap() {
// code here
}
我的问题是如何在我的源文件中实现这个 typedef?我有我的哈希函数(hashFunc),它接受一个常量字符串,并返回一个无符号整数,如下所示:
HashMap::hashFunc(const std::string& key)
{
unsigned int hashValue = 0; // what we end up returning
// hashFunc code here
return hashValue;
}
但是由于我必须在我的源文件中的构造函数、复制器等中使用这个散列函数,所以我应该从这个 typedef 中声明它。比如:
HashMap::HashMap(HashFunction hashFunc) { }
我怎样才能做到这一点?我已经尝试过诸如 HashFunction HashMap::hashFunc()、HashMap::HashFunction hashFunc() 和 HashMap::HashFunction::hashFunc() 之类的东西,但没有任何效果 :( 我是 C++ 新手,所以我意识到我可能看起来这个问题现在很愚蠢,但我不知道如何继续。
【问题讨论】:
-
“实现 typedef”是什么意思?它只是一个类型的别名。
-
我只是想把它放在我的类源文件中。由于 HashFunction HashMap::hashFunc(const std::string& key) { // code } 不能编译,而像 int HashMap::hashFunc(const std::string& key) { // code } 这样的东西会。
-
如果我发布的答案不充分,如果您将 HashMap.h 的内容附加到问题的末尾可能会有所帮助,这样我们就可以准确地看到您正在处理的限制。
标签: c++ function class typedef