mrsinister
mrsinister

Reputation: 97

Error in calling a function defined within a struct

I've been provided with a code to create a doubly-linked list. A node in the linked list is a struct by the name of ListItem. Now within that node is a function that assigns a value to the node. The problem that I'm having is that I can't seem to create a node and use the function to assign the value to it.

Here's the code for the struct "ListItem".

template <class T>
struct ListItem
{
    T value;
    ListItem<T> *next;
    ListItem<T> *prev;

    ListItem(T theVal)
    {
        this->value = theVal;
        this->next = NULL;
        this->prev = NULL;
    }
};

The corresponding ListItem functions in the accompanying .cpp file:

template <class T>
ListItem<T>* List<T>::getHead()
{
}

template <class T>
ListItem<T>* List<T>::getTail()
{
}

template <class T>
ListItem<T> *List<T>::searchFor(T item)
{
}

Here's what I was attempting to do in my main function.

int main()
{
    ListItem<int> a;
    a.ListItem(int 5);
    system("PAUSE");
}

All I'm trying to do here is create a node and assign a value to it. Following are the errors I'm getting:

='a' is not a class or namespace

=missing template arguments before '(' token

=expected primary expression before 'int'

Upvotes: 1

Views: 143

Answers (2)

Marius Bancila
Marius Bancila

Reputation: 16318

ListItem is not a function name, but the constructor of the class/structure. The constructor is a special function and cannot be called like that. Your code should look like this:

int main()
{
    ListItem<int> a(5);
    system("PAUSE");
}

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

Remember that a struct is just the same as a class, so what you've done is create a class with the name ListItem containing a normal constructor taking a single argument.

You create it like normal:

ListItem<int> a(5);

You have some other problems as well, like having functions for the class that are not declared in the class (e.g. the getHead function). You also can not have the implementation of templated function members in a separate source file, they have to be in the header file together with the class (or struct) definition.

Upvotes: 3

Related Questions