gpt4 book ai didi

使用模板的 C++ 链表

转载 作者:行者123 更新时间:2023-11-27 23:23:35 25 4
gpt4 key购买 nike

我想使用模板在 C++ 中实现我自己的链表。但是,我遇到了几个编译器错误。这是代码:

template <class T>
class Node{
T datum;
Node _next = NULL;
public:
Node(T datum)
{
this->datum = datum;
}
void setNext(Node next)
{
_next = next;
}
Node getNext()
{
return _next;
}
T getDatum()
{
return datum;
}
};
template <class T>
class LinkedList{
Node<T> *node;
Node<T> *currPtr;
Node<T> *next_pointer;
int size;
public:
LinkedList(T datum)
{
node = new Node<T>(datum);
currPtr = node; //assignment between two pointers.
size = 1;
}
void add(T datum)
{
Node<T> *temp = new Node<T>(datum);
(*currPtr).setNext((*temp));
currPtr = temp;
size++;
}
T next()
{
next_pointer = node;
T data = (*next_pointer).getDatum();
next_pointer = (*next_pointer).getNext();
return data;
}
int getSize()
{
return size;
}
};

当我尝试实例化这个类时,出现以下错误:

LinkedList.cpp: In instantiation of `Node<int>':
LinkedList.cpp:35: instantiated from `LinkedList<T>::LinkedList(T) [with T = int]'
LinkedList.cpp:60: instantiated from here
LinkedList.cpp:7: error: `Node<T>::_next' has incomplete type
LinkedList.cpp:5: error: declaration of `class Node<int>'
make[2]: *** [build/Debug/Cygwin-Windows/LinkedList.o] Error 1
make[1]: *** [.build-conf] Error 2
make: *** [.build-impl] Error 2

我正在使用 NetBeans IDE。有人可以给我一些改进建议吗?非常感谢!!

最佳答案

就像你做 Node<T> *node; 时一样在LinkedList , 你也需要在你的 Node 中做同样的事情类

template <class T>
class Node{
T datum;
Node<T> *_next;//template parameter
//also, need to make this a pointer and initialized in constructor
public:

//...
void setNext(Node<T> next) //template parameter
{
_next = next;
}
Node<T> getNext() //template parameter
{
return _next;
}
//...
};

关于使用模板的 C++ 链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11108207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com