泛型模版类出现了LNK2019: 无法解析的外部符号错误

我们在写程序的大部分时间都不会去考虑在已有的知识上出现的匮乏,前两天用C++写了一个顺序表,结果却不尽人意,这个或许是因为人生就是这样,在你已知的知识当中出现的知识漏洞你会很难发现,这里还是感谢一下syc大哥,每次在VC驿站上发帖子,他都给我回复了,也就是syc让我更加的喜欢VC驿站。

行了,谈谈出现的错误

这里是我之前出错的代码

http://www.cctry.com/thread-256893-1-1.html

这里我放上了我成功后的代码

SeqList.h

#include
#include
//默认的顺序表大小
const int defaultsize= 10;
//类
template
class SeqList
{
public:
	SeqList(int size = defaultsize)
	{
		//判断对应的顺序表长度
		if (size > 0)
		{
			maxSize = size;
			//数据数组
			eml = new DateType[size];
		}
	}
	//析构函数
	~SeqList()
	{
		//申请的数组不为空时进行释放
		if (eml != NULL)
		{
			delete []eml;
			eml = NULL;
		}
	}
	int getLength()
	{
		return curLength;
	}
	//插入
	bool insertElem(DateType e);
	//删除
	bool delElem(int index);
	//查找
	DateType findElem(int index);
	//更改
	bool changeElem(int index, DateType e);
private:
	DateType *eml;
	int maxSize;
	int curLength;
};
//插入
template
bool SeqList::insertElem(DateType e)
{
	if (curLength < maxSize)
	{
		eml[curLength] = e;
		curLength++;
		return true;
	}
	std::cout << "insertElem function the Array is full" << std::endl;
	return false;
}
//删除
template
bool SeqList::delElem(int index)
{
	if (curLength > index && index >= 0)
	{
		for (int i = index; i < curLength; i++)
		{
			eml[i] = eml[i + 1];
		}
		curLength--;
		return true;
	}
	std::cout << "delElem function wrong index" << std::endl;
	return false;

}

//查找
template
DateType SeqList::findElem(int index)
{
	if (index < 0 && index >= curLength)
	{
		std::cout << "findElem function wrong index" << std::endl;
		return NULL;
	}
	return eml[index];
}
//更改
template
bool SeqList::changeElem(int index, DateType e)
{
	if (index >= 0 && index < curLength)
	{
		eml[index] = e;
		return true;
	}
	std::cout << "changElem function wrong index" << std::endl;
	return false;
}

测试体

#include "SeqList.h"
#include 
//success in day 09-01
//模版类的声明和实现必须写在同一个头文件中,否则就无法找到类中对应的函数
int main()
{
	//使用泛型类,并调用构造函数
	SeqList list(10);
	//插入值
	for (int i = 0; i < 10; i++)
	{
		list.insertElem(i);
	}
	//显示值
	for (int i = 0; i < list.getLength(); i++)
	{
		std::cout << list.findElem(i) << std::endl;
	}
	//更改值
	list.changeElem(3, 5);
	list.delElem(4);
	//显示值
	for (int i = 0; i < list.getLength(); i++)
	{
		std::cout << list.findElem(i) << std::endl;
	}
	char a[10];
	std::cin >> a;


}

这里也就是说出现了一个小小的问题,就是模版类的定义和实现体一般要卸载同一个头文件中。

下面来源于网上:

在C++标准中没有明确规定,模版类的定义和实现体必须放置到同一个文件中,因为模版类是在预编译期间进行,如果写在两个文件中,增加了编译器的实现难度,所以大多数编译器一般都将模版类的定义和实现放置在同一个文件中。VS2005支持了模版类的分离编写,但是他又检测不出来很多其他的错误,这不得不说还是需要一个天才的大脑来解决这个问题

你可能感兴趣的:(C/C++经典)