2013-04-14 25 views
1

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

//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); // ERROR: undefined reference to Key<int>::Key(int)

然后用

songID.increment(); // ERROR: undefined reference to Key<int>::increment()

+0

首先,你必须把通用模板定义在同一个文件中的声明([见这里](http://stackoverflow.com/questions/648900/c-模板-未定义引用?RQ = 1))。其次,你可能不希望''中的''(KeyType initial);'或任何其他的。 – chris

回答