天天看點

為什麼類模闆中的函數的參數不能有預設值?

如題,在建立Hash表中,hash函數不能傳入預設參數為何?

#pragma once
#include <iostream>
using namespace std;
#include <string>

template <typename DataType>
class HashTable
{
public:
    HashTable(int size)
    {
        maxSize = size;
        count = 0;
        elements = new DataType[maxSize];
        if (elements == NULL)
            exit(1);
        else
        {
            for (int i = 0; i < maxSize; i++)
                elements[i] = NULL;
        }
    }
    ~HashTable()
    {
        delete[] elements;
    }

    int hash(DataType value,const int p=maxSize); //計算hash值
    int searchHash(DataType value);       //查找value值的位址
    DataType getData(int i)
    {
        if (i < 0)
        {
            cout << "索引值錯誤" << endl;
            exit(1);
        }
        return elements[i - 1];
    }
    bool insertHash(DataType);

private:
    int maxSize;
    int count;
    DataType *elements;
};

/*-----------------hash函數---------------*/
template <typename DataType>
int HashTable<DataType>::hash(DataType value,const int p=maxSize)
{
    return value % p;
}

/*-----------------查找算法---------------*/
template <typename DataType>
int HashTable<DataType>::searchHash(DataType value)
{
    int p = hash(value);
    if (elements[p] == value || elements[p] == NULL)
        return p;
    int rp = (p + 1) % maxSize;
    while (rp != p)
    {
        if (elements[rp] == value)
            return rp;
        if (elements[rp] == NULL) //如果不存在value
            break;
        rp = (rp + 1) % maxSize;
    }
    if (rp == p)
    {
        cout << "不存在" << endl;
        return -1;
    }
    else
    {
        // elements[rp] = value;
        return rp;
    }
}

/*-----------------插入算法---------------*/
template <typename DataType>
bool HashTable<DataType>::insertHash(DataType value)
{
    int p = searchHash(value);
    if (p < 0)
    {
        return false; //查找失敗,且hash表已滿
    }
    else if (elements[p] == value)
    {
        cout << "已有重複元素" << endl;
        return false;
    }
    else
    {
        elements[p] = value;
        return true;
    }
}
           

繼續閱讀