带有类模板的C++未解析外部符号
C++ Unresolved external symbol with Class templates
这里有一个在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
文件)。
编译模板类时,编译器如何知道要生成哪些类?
相关文章:
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- 未解析的外部符号_MsiLocateComponentW@12.
- 在C++中使用 gRPC 时未解析的外部符号
- LibPrivoxy: 未解析的外部符号 __declspec(dllimport) int __stdcall Sta
- 尝试从 XamlApplication 编译 C++/WinRT 空白应用程序时,我收到未解析的外部符号 winrt_make_*
- 我收到错误LNK2001:未解析的外部符号(C++代码)
- 可视抽象类 c++(错误 LNK 2001:未解析的外部符号)
- 如何摆脱C++中未解析的外部符号"private: static char"错误?
- 当 lib 已添加到其他依赖项时,如何在 VS 中调试未解析的外部符号错误
- 仅在少数方法(静态或共享库)中解析的外部符号
- 未解析的外部符号"__declspec(dllimport)与 Spdlog c++ 库
- 函数 _main (OPENGL C++) 中引用的未解析的外部符号 ________
- 错误LNK2019未解析的外部符号"public: __thiscall SLinkList<char>::SLinkList<char>(void)"
- 使用静态 constexpr 成员的未解析外部符号
- 引入参数化构造函数后显示 LNK 2019 未解析外部符号的代码错误
- Dlib LNK2001未解析的外部符号USER_ERROR__consistent_build_configurati
- 矛盾的未解决的外部符号+未使用的库与VS2017和FFMPEG 4
- 链接器错误:切换到unicode生成给出:未解析的外部符号WinMain
- 类模板上一个特定函数的未解析外部符号
- LNK2001:未解析的外部符号public:static类std::vector