我是 C++ 模板的新手。我目前正在做一个项目,我需要使用模板来实现双向链表。这是目前我所拥有的:
template<class ItemType>
class SortedList
{
public:
SortedList();
~SortedList();
bool Insert (ItemType toAdd);
bool Delete (ItemType toDelete);
void Print();
private:
SortedList ( const SortedList & copyFrom );
SortedList & operator= ( const SortedList & assignFrom );
struct Node
{
Node ( ItemType item, Node * p = NULL, Node * n = NULL )
{ data = item; prev = p; next = n; }
ItemType data;
Node * prev, * next;
};
Node * list;
};
template<class ItemType>
SortedList<ItemType>::SortedList()
{
list == NULL;
}
template<class ItemType>
SortedList<ItemType>::~SortedList()
{
Node * curr = list;
while ( curr != NULL )
{
Node * tempNext = curr->next;
delete current;
current = tempNext;
}
}
但是,例如在我的析构函数中,为什么我不能访问节点元素?该方法中的代码现在已编译,但不会抛出错误。但是,如果我尝试在 curr 上使用 ->,next 或 prev 不会出现。为什么我无法访问这些?我觉得我在这里缺少一些非常明显的东西来开始。
此外,如何在函数头中初始化 list == NULL,而不是在类之外进行初始化?
最佳答案
- 不知道它为什么编译,但你正在使用
删除当前;
当前 = tempNext;
代替:
delete curr;
curr = tempNext;
- 使用内联初始化语法:
类 SortedList
{
民众:
排序列表()
:
列表(nullptr)
{}
- 使用相同的语法初始化 Node(更优)
关于c++ - (C++) 双向链表模板 - 访问问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26601207/