【问题标题】:C++ adding item onto a linked list [duplicate]C ++将项目添加到链表中[重复]
【发布时间】:2014-05-08 15:52:26
【问题描述】:

我正在尝试将节点添加到链表的开头(推送功能)。我收到 2 个错误:

1) 从 'Node int*' 到 'int' 的无效转换(指向 test.Push(&test2); in main())

2) 初始化 'int Linked_List::Push(Ite​​mType) [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&lt;int&gt; 指针?为什么 main() 甚至参与使用Nodes?搞清楚如何创建和维护Nodes 不是 Linked_List 类的职责吗?
  • “如果我删除 & .. 那么我会得到更多的错误,所以我认为它是正确的。”这不一定是真的。你实际上是Programming by Coincidence。请阅读 C++。
  • 谢谢我让这部分工作。现在有人可以告诉我为什么 Node *nnode = new node; 不起作用吗?说错误:“节点”之前的预期类型说明符。还有其他方法可以做到吗?

标签: c++ class templates linked-list


【解决方案1】:

您的函数签名需要ItemType,在您的情况下为int

int Push(ItemType newitem);

但您尝试传递Node&lt;ItemType&gt;,因此您收到错误消息。

您的Push 函数已经在内部创建了一个节点,因此您可以将整数直接传递给它:

Linked_List <int> test;
int test2 = 4;
test.Push(test2);

我需要指出,除此之外,您的代码还有其他几个问题 - 对于初学者来说,这个 sn-p:

Node <ItemType> *nnode;  //create new node to store new item

是否创建节点 - 它只是声明一个指针。

我强烈建议您阅读 C++ 的基础知识。

【讨论】:

  • 我想我评论错了,但它应该仍然可以作为链接列表使用,对吧?
  • @Foxic 好吧,Push 和列表类中的其他函数有责任确保这一点。您班级的用户甚至不需要知道其中涉及“节点”。
【解决方案2】:

Push 采用模板类型,在这种情况下为 int。你想要做的是这样的:

Linked_List<int> test;
test.push(4);

【讨论】:

  • 现在我的程序刚刚关闭,“*.exe 已停止工作”,不知道如何调试,所以 idk 如果你能帮忙的话
  • @Foxic 随时提出一个新问题,如果它解决了您当前的问题(编译器错误),请在此处将其中一个答案标记为已接受。
  • @Foxic - 如果您编写这样的程序,您必须知道如何调试它们(不一定知道,不一定知道,但必须知道)。现在是学习如何使用编译器调试器的时候了。那你用的是什么编译器?
  • 明威。问题在于 Push 中包含“->”的行。我想添加 node = new node 希望它能修复它,但它只是说 "expected type-specifier before 'node'" “预期;在‘节点’之前”
  • @Foxic - I want to add node = new node&lt;ItemType&gt; in hopes it'll fix it 听起来你只是在往墙上扔东西,希望有东西能粘住。你无法以这种方式学习编程,尤其是 C++ 编程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 2020-08-04
  • 2018-06-18
  • 2021-12-23
  • 1970-01-01
  • 2021-03-05
相关资源
最近更新 更多