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()
首先,你必須把通用模板定義在同一個文件中的聲明([見這裏](http://stackoverflow.com/questions/648900/c-模板-未定義引用?RQ = 1))。其次,你可能不希望''中的''(KeyType initial);'或任何其他的。 –
chris