Frage

I'm trying to add a node onto the beginning of a linked list (push function). I'm getting 2 errors:

1) invalid conversion from 'Node int*' to 'int' (points to test.Push(&test2); in main())

2) initializing argument 1 of 'int Linked_List::Push(ItemType) [with ItemType = int]' (points to function push)

I'm really not sure what the problem is. If I remove the & out of test.Push(&test2); in main() then I get a lot more errors, so I assume it's correct.

//.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
}
War es hilfreich?

Lösung

Your function's signature expects a ItemType, which is int in your case:

int Push(ItemType newitem);

But you are trying to pass a Node<ItemType>, hence you get an error.

Your Push function is already creating a a node internally, so you'd pass the integer directly into it:

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

I need to point out that your code has several other problems besides that, though - for starters, this snippet:

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

Does not create a Node - it just declares a pointer.

I'd strongly advise you to read up on C++'s basics.

Andere Tipps

Push takes the template type, so int in this case. What you want to do is something like:

Linked_List<int> test;
test.push(4);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top