对使用模板的类的未定义引用
C++ undefined reference to class that uses template
我是一个很新的模板,所以请不要对我苛刻,如果我的代码是非常错误的:)这是使用模板的类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文件中?
相关文章:
- 编译C++时未定义的引用
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 未定义的引用在哪里
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 对 Scalar ::Scalar() 的未定义引用
- 已定义函数时出现 G++ "未定义的引用"错误
- 链接 cmake 时出现未定义的引用错误
- 对复制 CTOR 和 CTOR 的未定义引用
- 错误:未定义对'oboe::AudioStreamBuilder::openStream(oboe::AudioStream**)'的引用
- 右值引用未定义的行为
- 对"vtable for DigitalClock"的未定义引用 - 未定义对"DigitalClock::staticMetaObject"的引用 - Qt
- 函数类型到函数类型的引用:未定义的引用
- avcodec_alloc_context引用未定义,但ffmpeg链接顺序正确
- 从c++调用Fortran子程序,链接时引用未定义
- 枚举引用未定义,但位于包含的头文件中