編輯 - 在下面回答,錯過了有角度的大括號。謝謝大家。C++模板 - LinkedList
我一直在試圖編寫一個基本的單向鏈表,我可以在其他程序中使用它。我希望它能夠使用內置和用戶定義的類型,這意味着它必須是模板化的。
由於這我的節點也必須模板化,因爲我不知道它將要存儲的信息。
template <class T> class Node
{
T data; //the object information
Node* next; //pointer to the next node element
public:
//Methods omitted for brevity
};
我的鏈表類是在一個單獨的類中實現,並且需要將新節點添加到列表的末尾,當實例化一個節點 - 我有如下寫了一個節點類。我已經實現了這個原則 -
#include <iostream>
#include "Node.h"
using namespace std;
template <class T> class CustomLinkedList
{
Node<T> *head, *tail;
public:
CustomLinkedList()
{
head = NULL;
tail = NULL;
}
~CustomLinkedList()
{
}
//Method adds info to the end of the list
void add(T info)
{
if(head == NULL) //if our list is currently empty
{
head = new Node<T>; //Create new node of type T
head->setData(info);
tail = head;
}
else //if not empty add to the end and move the tail
{
Node* temp = new Node<T>;
temp->setData(info);
temp->setNextNull();
tail->setNext(temp);
tail = tail->getNext();
}
}
//print method omitted
};
我已成立了一個驅動器/測試類如下 -
#include "CustomLinkedList.h"
using namespace std;
int main()
{
CustomLinkedList<int> firstList;
firstList.add(32);
firstList.printlist();
//Pause the program until input is received
int i;
cin >> i;
return 0;
}
我在編譯時得到一個錯誤,但是 - 錯誤C2955:「節點」:使用類模板需要模板參數列表 - 這點我在我的add方法,把下面的代碼行 -
Node* temp = new Node<T>;
我不明白爲什麼日沒有關於類型的信息,因爲它在我的驅動程序類中創建時傳遞給鏈接列表。 我應該如何將類型信息傳遞給Node?
我應該創建一個私有的節點結構而不是一個單獨的類,並將兩個類的方法合併到一個文件中嗎?我不確定這會克服這個問題,但我認爲它可能會。如果可能的話,我寧願有單獨的課程。
謝謝,安德魯。
謝謝。愚蠢的錯誤在我的角色。乾杯。 – 2010-01-16 23:30:33
你知道C++標準庫已經提供了一個雙向鏈表模板(std :: list)嗎?此外,Boost庫提供了「侵入式」鏈接列表。 – 2010-01-17 01:36:06
是的,我知道,但是製作你自己的應該是很好的練習,特別是對於指針邏輯。另外我想實現一些方法有點不同。感謝您的建議,但。 – 2010-01-17 13:47:47