简体   繁体   中英

c++ Template Class member functions, reliance on other template classes

I am trying to create a linked list class that uses a node class as the nodes within the list (Next node, data). The Linked List class acts as a header for the list which contains the member functions and can be used with any datatype (ie the templates). I am having difficulty understanding how the templates work within the class declarations and member function implementation.

I have two template classes for the linked list (here are the relevant parts):

template<typename NodeObjectType>
class ListNode
{
public:
    NodeObjectType data;
    ListNode<NodeObjectType>* next;
    ListNode() : next(NULL){}
    ListNode(const NodeObjectType& item, ListNode<NodeObjectType>* nextNode = NULL)
    {
        data = item;
        next = nextNode;
    }
};

template<typename ObjectType>
class myList
{
public:
    myList()
    {
        Head = NULL;
    }

    // Other member Functions    ...


    bool contain(ObjectType x)
    {
        ListNode<ObjectType> *current = Head;
        while ( current != NULL )
        {
            if (current->data == x)
                return true;
            current = current->next ; // move forward one step
        }
        return false;
    }


    void add(ObjectType x)
    {
        if(!contain(x))
        {
            ListNode<ObjectType>* NewListNode(x , Head);
            Head = NewListNode;
        }
    }

private:
    ListNode<ObjectType>* Head;
};

On compilation I get the error

In instantiation of 'void myList<ObjectType>::add(ObjectType) [with ObjectType = int]':
required from here
error: expression list treated as compound expression in initializer [-fpermissive]

Am I doing the template object type passing incorrectly or is it something else? Thank you

The line:

ListNode<ObjectType>* NewListNode(x , Head);

should be:

ListNode<ObjectType>* NewListNode = new ListNode<ObjectType>(x , Head);
//                                ~~~~~~~~~~~~~~~~~~~~~~~~~^  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM