在看《大化数据结构》的过程中,出现了类模板的定义,由于自己c++编写能力并不是很好,自己写了一个类模板,无论怎么写都出现如下错误:
错误 3 error LNK1120: 2 个无法解析的外部命令 F:\leetcode\Sqlist\Debug\Sqlist.exe Sqlist
错误 1 error LNK2019: 无法解析的外部符号 "public: __thiscall List<int>::List<int>(int * const,int)" (??0?$List@H@@QAE@QAHH@Z),该符号在函数 _wmain 中被引用 F:\leetcode\Sqlist\Sqlist\Sqlist.obj Sqlist
但是写一般的类就没问题,搞了半天才知道,类模板的定义与实现最好写在同一个文件中,即声明与实现放到一起,具体为啥减下面的博客:
https://blog.youkuaiyun.com/lichengyu/article/details/6792135
***********************************************************************************************************************
test.h文件:
#ifndef TEST_H
#define TEST_H
#include "stdafx.h"
template <class DataType>
class List{
public:
List(DataType a[], int n);
//~List();
bool push(DataType a, int n);
private:
DataType data[10];
int len;
};
#endif
***********************************************************************************************************************
test.cpp文件:
tem#include "stdafx.h"
#include "test.h"
plate<class DataType>
List<DataType>::List(DataType a[], int n){
for (int i = 0; i < n; i++){
data[i] = a[i];
}
}
template<class DataType>
bool List<DataType>::push(DataType a, int n){
data[n] = a;
return 1;
}
***********************************************************************************************************************
main文件:
#include "stdafx.h"
#include "SeqList.h"
#include "iostream"
#include "test.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int a[3] = { 1, 2, 3 };
/*SeqList<int>list(a,3);
int data;
list.GetElem(list, 1, &data);
cout << "data is :" << data << endl*/;
List<int> list(a,3);
//List<int> list;
list.push(0, 3);
return 0;
}
将上述test.cpp中的代码放到test.h中就不会报错了,共勉。