对使用模板的类的未定义引用

C++ undefined reference to class that uses template

本文关键字:引用 未定义      更新时间:2023-10-16

我是一个很新的模板,所以请不要对我苛刻,如果我的代码是非常错误的:)这是使用模板的类Key的头文件:

//Key.h
#ifndef KEY_H
#define KEY_H
#include "../Constants.h"
template<class KeyType>
class Key
{
    public:
        Key<KeyType>(KeyType initial);          
        KeyType increment();
    private:
        KeyType current;
};
#endif /* KEY_H */ 

Key类的。cpp文件:

//Key.cpp
#include "Key.h"
template<class KeyType> Key<KeyType>::Key(KeyType p_initial)
{
    this->current = p_initial;
}
template<class KeyType> KeyType Key<KeyType>::increment()
{
    this->current ++; //KeyType should implement this operator
}

那么问题是什么?我尝试在我的代码的其他地方创建Key的实例,像这样:

Key songID (0);//错误:未定义的Key<int>::Key(int)引用

,然后使用

songID.increment ();//错误:对Key<int>::increment()的未定义引用

两点:

  • <KeyType>从不需要的Key<KeyType>(KeyType initial);中移除

  • 并且,将类实现从.cpp文件移动到.h文件。这篇文章很有用:为什么我不能将模板类的定义与其声明分开,并将其放入.cpp文件中?