我试图在C++中实现通用链接的对象列表。但是,当我两次获取同一个对象时,它给了我不同的结果。我觉得这是由于滥用指针。请帮我调试。c中的通用链接列表C++实现
这是Node的实现。我已经使用了模板指针,因为链接列表应包含用户定义的对象。
template <class T> class Node{
private:
T* value;
Node<T>* next;
public:
Node(T* v){value = v; next = NULL;}
Node(T* v, Node<T>* n){value = v; next = n;}
T* getElement(){return value;}
Node<T>* getNext(){return next;}
};
这是通用链接列表的实现。
template <class T> class LinkedList{
public:
Node<T>* head = NULL;
LinkedList(){}
LinkedList(T* value){
Node<T> node(value);
head = &node;
}
Node<T>* getHead(){
return head;
}
void add(T* value){
Node<T> node(value,head);
head = &node;
}
};
主要功能: 当我打电话链表的头,它给了我2个不同的答案。在这段代码中,Complex是一个容纳复杂对象的简单类。
int main(){
Complex c1(1,2); Complex c2(3,4); Complex c3(5,6);
LinkedList<Complex> list(&c1);
list.add(&c2);
cout<<list.head->getElement()->i<<" "<<list.getHead()->getElement()->j<<endl;
cout<<list.head->getElement()->i<<" "<<list.getHead()->getElement()->j<<endl;
return 0;
}
在此先感谢!
'C'没有类,所以你不能用'classes'在'C'中实现一个类。尝试使用结构。 –
使用您的调试器。 SO不是调试服务。在追踪问题后,您可以问一个问题,如果您不明白为什么代码正在执行的方式,但在此时您将掌握所发生的问题的所有细节。 –
为什么不使用'std :: list'并完成它呢? –