C++ 模板 LINK2019报错的问题

在自定义类的头文件中使用了模板,在模板实例化时,编译器无法找到模板的实现,会报错LINK2019

  • 解决方法1:在使用了模板类或模板函数的文件中同时包含类定义的 .h 文件和同名的 .cpp 文件(即实现了类中的各个函数的文件)。
// file: test.h

template <T>
class Test {
private:
    T key;
    
public:
    // 函数声明
    void func();
};
// file: test.cpp

// 函数实现
void Test<int>::func() {
    // code
    // 
}
#include "test.h"
#include "test.cpp"

int main() {

    // 可以使用该头文件中的类模版
}
  • 解决方法2:(推荐)将声明与实现写在一个文件里,命名.hpp
// file: test.hpp

template <T>
class Test {
private:
    T key;
    
public:
    // 函数声明
    void func();
};

// 函数实现
void Test<int>::func() {
    // code
    // 
}
#include "test.hpp"  // 包含该头文件就可以使用模板类

int main() {
	
	Test<int> t;  // OK
}

posted @ 2022-10-24 21:29  Bdathe  阅读(223)  评论(0)    收藏  举报