【发布时间】:2014-05-08 15:52:26
【问题描述】:
我正在尝试将节点添加到链表的开头(推送功能)。我收到 2 个错误:
1) 从 'Node int*' 到 'int' 的无效转换(指向 test.Push(&test2); in main())
2) 初始化 'int Linked_List::Push(ItemType) [with ItemType = int]' 的参数 1(指向函数 push)
我真的不确定问题出在哪里。如果我在 main() 中从 test.Push(&test2); 中删除 & ,那么我会得到更多错误,所以我认为它是正确的。
//.h
#ifndef Linked_List_h
#define Linked_List_h
template <typename ItemType>
class Node
{
public:
ItemType Data;
Node <ItemType> *next;
};
template <typename ItemType>
class Linked_List
{
public:
Node <ItemType> *start;
Linked_List();
int Push(ItemType newitem);
};
#endif
.
//.cpp
#include "Linked_List.h"
template <typename ItemType>
Linked_List <ItemType>::Linked_List(){
start = NULL;
}
template <typename ItemType>
int Linked_List <ItemType>::Push(const ItemType newitem){ //error
Node <ItemType> *nnode; //create new node to store new item
nnode -> next = start -> next; //new item now points previous first item of list
start -> next = nnode; //'start' pointer now points to the new first item of list
return 1;
}
int main(){
Linked_List <int> test;
Node <int> test2;
test2.Data = 4;
test.Push(&test2); //error
}
【问题讨论】:
-
请先阅读this。
-
@Foxic - 您的
Linked_List类使用int作为模板参数。你为什么要推Node<int>指针?为什么 main() 甚至参与使用Nodes?搞清楚如何创建和维护Nodes 不是 Linked_List 类的职责吗? -
“如果我删除 & .. 那么我会得到更多的错误,所以我认为它是正确的。”这不一定是真的。你实际上是Programming by Coincidence。请阅读 C++。
-
谢谢我让这部分工作。现在有人可以告诉我为什么 Node
*nnode = new node 不起作用吗?说错误:“节点”之前的预期类型说明符。还有其他方法可以做到吗?;
标签: c++ class templates linked-list