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

标签 c++ templates compiler-errors undefined-reference

<分区>

我对模板很陌生,所以如果我的代码有很大错误,请不要对我太苛刻 :) 这是使用模板的类 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); // ERROR: undefined reference to Key<int>::Key(int)

然后使用

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

最佳答案

两点:

关于C++ 未定义对使用模板的类的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15996272/

相关文章:

c++ - 为什么在 Directshow 中捕获图形不起作用?

C++ MySQL 驱动程序->连接 vs2017 未加载符号

c++ - 有没有线程太多这样的事情?

c++ - 带有 MinGW 4.8 的 Windows 上的模板 undefined reference

c++ - 如何模板化部分模板特化?

c++ - 重新声明模板参数

c++ - "cv-unqualified"在 C++ 中是什么意思?

C# 代码显示错误 "A namespace cannot directly contain members such as fields or methods"

c++ - 无法访问 Arduino 结构字段。错误 "exit status 1. xxxx does not name a type"

perl - 编译错误: Requires Explicit Package Name