【发布时间】:2013-12-18 07:01:05
【问题描述】:
这是一个在 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:\Programming\C++\stuff\templass\Debug\templass.exe : fatal error LNK1120: 2 unresolved externals
我使用 Microsoft Visual C++ 2010 Express。所以我搜索了很多关于未解析的外部符号,但没有找到这个案例。那么我的错误是什么?
【问题讨论】:
-
“所以我搜索了很多关于未解析的外部符号,但没有找到这个案例。”真的吗?一个简单的谷歌搜索“模板未解析的外部符号”给你确切的解决方案。
标签: c++ class templates external