在此类的函数中使用来自另一个类或结构的函数

时间:2014-02-17 04:09:06

标签: c++ class c++11 hashtable

我正在创建一个哈希表,需要使用不同的哈希函数测试这个链式哈希表。 我有哈希结构,如

struct Hasher {
    virtual int hash(std::string s, int N) = 0;
};

struct SumHasher : Hasher {
    int hash(std::string s, int N){
        int result = 0;
        for (int i=0; i<s.size(); ++i)
            result += s[i];
        return int (std::abs((int)result)) % N;
    }
};
struct ProdHasher : Hasher {
    int hash(std::string s, int N) {
        int result = 1;
        for (int i=0; i<s.size(); ++i)
        result *= s[i];
    return int (std::abs((int)result)) % N;
    }
};
struct ShiftHasher : Hasher {
    int hash(std::string s, int N){
    const int shift = 6; unsigned z = 0;
    const int mask = ~z >> (32-shift); // lower 6 bits on
    int result = 0;
    for (int i = 0; i < s.length(); i++)
        result = (result << shift) | (s[i] & mask);
    return int (std::abs((int)result)) % N;
    }
};

现在我如何在Hashtable类中使用此函数,方法是创建一个struct hash类型,然后将该对象传递给构造函数

class ChainedHashTable
{

    ListNode **T; // array of linked lists
    int capacity;
public:
    Hasher *myhash;
    int info;
    ChainedHashTable(int numberOfChains, Hasher *myHasher){
        myhash = hasher;
        capacity = numberOfChains;
       T = new ListNode* [capacity];
       for (int i=0; i<capacity; ++i)
           T[i] = NULL;
     }
.......
void ChainedHashTable::insert(std::string key, int info){
    int h = myhash::hash(key, capacity);
    T[h] = ListNode::make(key, info, T[h]);
}

1 个答案:

答案 0 :(得分:1)

你应该使用:

myhash->hash(key, capacity)