gdw66
gdw66
采纳率0%
2021-03-01 15:19

使用c++编写一个类模板及其特化类,测试报错

#include <exception>
#include <stdexcept>
#include <string>
#include <iostream>

using namespace std;

//类模板
template <typename T>
class DefaultHash {
public:
    DefaultHash(size_t mNumBuckets = 101) throw(invalid_argument);
    size_t hash(const T& key) const;
    size_t numBuckets() const{return  mNumBuckets;}

protected:
    size_t mNumBuckets;
};


template<typename T>
DefaultHash<T>::DefaultHash(size_t numBuckets) throw(invalid_argument){
    if (numBuckets<=0) {
        throw invalid_argument("numBcukets must be > 0");
    }
    mNumBuckets = numBuckets;
}

template<typename T>
size_t  DefaultHash<T>::hash(const T& key) const{
    size_t bytes=sizeof(key);
    size_t res=0;
    for (size_t i=0; i<bytes; ++i) {
        unsigned char b=*((unsigned char*)&key+i);
        res+=b;
    }
    return res % mNumBuckets;
}

//模板特化为string类型

template<>
class DefaultHash<string>{

public:
    DefaultHash(size_t numBuckets=101) throw(invalid_argument);
    size_t hash(const string& key) const;
    size_t numBuckets() const{return  mNumBuckets;}
protected:
    size_t mNumBuckets;

};


DefaultHash<string>::DefaultHash(size_t numBuckets) throw(invalid_argument)
{
    if (numBuckets<=0) {
        throw invalid_argument("numBcukets must be > 0");
    }
    mNumBuckets = numBuckets;
}

size_t DefaultHash<string>::hash(const string& key) const{

    size_t sum=0;
    for (size_t i=0; i< key.size(); ++i) {
        sum += (unsigned char)key[i];

    }

    return sum % mNumBuckets;
}

//测试函数

void testDefaultHash(){

    DefaultHash<int> myIntHash(500);
    cout<<myIntHash.hash(100)<<"  ";


    DefaultHash<string> myStringHash(500);
    cout<<"key=yht:"<< myStringHash.hash("yht")<<" "<<endl;
    cout<<"mNumBuckets="<<myStringHash.numBuckets()<<endl ;
}

在main函数中调用testDefaultHash(),单独测试特化的模板类不报错,测试模板类时报下面错误:

Undefined symbols for architecture x86_64:

  "DefaultHash<int>::DefaultHash(unsigned long)", referenced from:

      testDefaultHash() in TestHeader.o

  "DefaultHash<int>::hash(int const&) const", referenced from:

      testDefaultHash() in TestHeader.o

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • gdw66 gdw66 1月前

    把DefaultHash <typename T>类模板的声明和实现放在都放在.h文件中,就可以了.

    点赞 评论 复制链接分享

为你推荐