模板类 error LNK2019: 无法解析的外部符号

时间:2021-11-18 21:15:13

如果将类模板的声明和实现写在两个独立的文件中,在构建时会出现“error LNK2019: 无法解析的外部符号 ”的错误。

解决方法有:

  • 第一种方法,就是把类模板中成员函数的声明和定义都放在类的定义中(.h文件),不要分开就行。
  • 第二种方法,在主文件(main文件)中既包含类模板的声明文件(接口文件)(.h文件),同时也包含类模板的实现文件(.cpp文件)就行了。
  • 第三种方法,在类的定义中(.h文件)的最后包含类模板的实现文件(.cpp文件)。

 

原因在于模板类和模板函数在使用的时候才会被实例化。当模板被使用时,编译器需要函数所有的实现代码,来用合适的类型(模板参数)去构建正确的函数。但是如果将函数实现在单独的源文件中,这些文件是不可见的,因而会出错。

 

下面是摘自 *的回答

Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:

template<typename T>
struct Foo
{
T bar;
void doSomething(T param) {/* do stuff using T */ }
}; // somewhere in a .cpp
Foo<int> f;

When reading this line, the compiler will create a new class (let's call it FooInt), which is equivalent to the following:

struct FooInt
{
int bar;
void doSomething(int param) {/* do stuff using int */ }
}

Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.

 

 

参考:

CSDN:模板类 error LNK2019: 无法解析的外部符号 

*:Why can templates only be implemented in the header file?