带有类模板的C++未解析外部符号

C++ Unresolved external symbol with Class templates

本文关键字:外部 符号 C++      更新时间:2023-10-16

这里有一个在C++中使用类模板的简单示例。此代码有效。

#include <iostream>
using namespace std;
template <class T>
class Test {
public:
   Test();
   void print();
private:
    int i;
};
template <class T>
Test<T>::Test() {
    i=1;
    cout<<"New instance"<<endl;
}
template <class T>
void Test<T>::print() {
    cout<<"Test"<<endl;
}
int main() {
    Test<int> i;
    i.print();
    return 0;
}

因此,当我将这些代码分为3个文件时:main.cpp、Test.h、Test.cpp:

//Test.h
#include <iostream>
using namespace std;
template <class T>
class Test {
public:
   Test();
   void print();
private:
    int i;
};
//Test.cpp
#include "Test.h"
template <class T>
Test<T>::Test() {
    i=1;
    cout<<"New instance"<<endl;
}
template <class T>
void Test<T>::print() {
    cout<<"Test"<<endl;
}
//main.cpp
#include "Test.h"
using namespace std;
int main() {
    Test<int> i;
    i.print();
    return 0;
}

我得到一个错误:

1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall Test<int>::print(void)" (?print@?$Test@H@@QAEXXZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Test<int>::Test<int>(void)" (??0?$Test@H@@QAE@XZ) referenced in function _mai
1>C:ProgrammingC++stufftemplassDebugtemplass.exe : fatal error LNK1120: 2 unresolved externals

我使用Microsoft Visual C++2010学习版。所以我搜索了很多关于未解决的外部符号的信息,但在这个案例中没有找到。那么我错在哪里呢?

不能像编译任何其他源文件一样编译模板。接口和实现都应该位于头文件中(尽管有些将它们拆分为接口的.hpp文件和实现的.ipp文件,然后在.hpp文件的末尾包含.ipp文件)。

编译模板类时,编译器如何知道要生成哪些类?