泛型模版類出現了LNK2019: 無法解析的外部符號錯誤

我們在寫程序的大部分時間都不會去考慮在已有的知識上出現的匱乏,前兩天用C++寫了一個順序表,結果卻不盡人意,這個或許是因爲人生就是這樣,在你已知的知識當中出現的知識漏洞你會很難發現,這裏還是感謝一下syc大哥,每次在VC驛站上發帖子,他都給我回復了,也就是syc讓我更加的喜歡VC驛站。

行了,談談出現的錯誤

這裏是我之前出錯的代碼

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

這裏我放上了我成功後的代碼

SeqList.h

#include<iostream>
#include<stdio.h>
//默認的順序表大小
const int defaultsize= 10;
//類
template<typename DateType>
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<class DateType>
bool SeqList<DateType>::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<class DateType>
bool SeqList<DateType>::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<class DateType>
DateType SeqList<DateType>::findElem(int index)
{
	if (index < 0 && index >= curLength)
	{
		std::cout << "findElem function wrong index" << std::endl;
		return NULL;
	}
	return eml[index];
}
//更改
template<class DateType>
bool SeqList<DateType>::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 <iostream>
//success in day 09-01
//模版類的聲明和實現必須寫在同一個頭文件中,否則就無法找到類中對應的函數
int main()
{
	//使用泛型類,並調用構造函數
	SeqList<int> 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支持了模版類的分離編寫,但是他又檢測不出來很多其他的錯誤,這不得不說還是需要一個天才的大腦來解決這個問題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章