所以我一直在研究一個帶有節點結構的鏈表類。當我在類之前定義模板化結構時,該類可以作業,但是在類的私有部分中宣告時它不起作用。我特別需要使用模板 T 在類私有部分中定義 ListNode 結構。
#include <iostream>
using namespace std;
template <typename T>
class LinkedList
{
public:
LinkedList()
{
head = NULL;
tail = NULL;
numNodes = 0;
}
~LinkedList()
{
}
int getLength()
{
return numNodes;
}
T getNodeValue(int value)
{
ListNode<T> *indexNode;
indexNode = head;
int i = 0;
if (value < 0 || value > numNodes - 1)
{
throw;
}
while (indexNode->next != NULL)
{
if (i == value)
{
break;
}
indexNode = indexNode->next;
i ;
}
return indexNode->contents;
}
void insertNode(ListNode<T> *newNode)
{
if (head == NULL)
{
head = newNode;
tail = head;
tail->next = NULL;
numNodes ;
return;
}
if (newNode->contents <= head->contents)
{
if (head == tail)
{
head = newNode;
head->next = tail;
}
else
{
ListNode<T> *placeholder;
placeholder = head;
head = newNode;
head->next = placeholder;
}
numNodes ;
return;
}
if (newNode->contents > tail->contents)
{
if (head == tail)
{
tail = newNode;
head->next = tail;
}
else
{
ListNode<T> *placeholder;
placeholder = tail;
tail = newNode;
placeholder->next = tail;
}
numNodes ;
return;
}
ListNode<T> *indexNode;
indexNode = head;
while (indexNode->next != NULL)
{
if (newNode->contents <= indexNode->next->contents)
{
newNode->next = indexNode->next;
indexNode->next = newNode;
numNodes ;
return;
}
indexNode = indexNode->next;
}
}
private:
template <typename T>
struct ListNode
{
ListNode()
{
next = NULL;
}
ListNode(T value)
{
contents = value;
next = NULL;
}
T contents;
ListNode<T> *next;
};
ListNode<T> *head;
ListNode<T> *tail;
int numNodes;
};
#endif
uj5u.com熱心網友回復:
您的結構ListNode不必是模板,因為它已經是在模板類中定義的嵌套型別。
只需像這樣定義它:
struct ListNode
{
ListNode()
{
next = NULL;
}
ListNode(T value)
{
contents = value;
next = NULL;
}
T contents;
ListNode *next;
};
然后只需使用LinkedList<T>::ListNode(或僅ListNode在課堂內使用)。
例如,成員head和tail成為:
ListNode *head;
ListNode *tail;
重要提示:如果結構體在公共函式中使用(例如:),則不能在私有部分中定義該結構體void insertNode(ListNode *newNode)。否則,你應該如何創建一個從課堂外ListNode呼叫insertNode的?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/312597.html
上一篇:為什么會明確地選擇左值參考多載而不是左值的轉發參考多載?
下一篇:C 20中模板類的概念
