Hi,
I wrote a template for a double linked list and i try to dynamically allocate an array where each element is a list from that template, but when i try to insert an element i get a compilation error and i don't understand the reason for getting this.
Here's the code:
template array definition:
Code:
List <gift> *buckets;
inserting the element:
Code:
gift * newGift;
...
...
buckets[pos].insertNode (*newGift);
element insertion code
Code:
template <class contain>
int List<contain>::insertNode (contain &element)
{
ListNode <contain> *temp, *newNode;
// if first element allocate first pointer.
if (!size) {
list = new ListNode <contain> (element);
lastNode = list;
return ++size;
}
//else traverse the list and insert element at the end.
temp = list;
while (temp -> getNext())
temp = temp -> getNext();
//if memory allocation error return 0
if (!(newNode = new ListNode <contain> (element))) return 0;
temp -> setNext (newNode);
lastNode = newNode;
return ++size; // else return the size of the list
}
and compiler error:
Code:
list.cpp: In member function ‘int List<contain>::insertNode(contain&) [with contain = gift]’:
santa.cpp:41: instantiated from here
list.cpp:48: error: could not convert ‘temp->ListNode<contain>::getNext [with contain = gift]()’ to ‘bool’
list.cpp:49: error: cannot convert ‘ListNode<gift>’ to ‘ListNode<gift>*’ in assignment
If any additional information is needed please let me know.
Thanks in advance.
so you should show us your definition of ListNode and ListNode::getNext().
More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf
Premature optimization is the root of all evil --Donald E. Knuth
getNext returns a REFERENCE, as such it must ALWAYS be a valid object. Therefore the if statement is illegal. Ift is the same as:
Code:
class A {};
A a;
if (a) {...}
TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!) 2008, 2009 In theory, there is no difference between theory and paractice; in practice there is.
* Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
* How NOT to post a question here
* Of course you read this carefully before you posted
* Need homework help? Read this first
In your constructor of ListNode you set next to 0. Calling getNext() on such an object will result in dereferencing the null pointer, which will probably crash your program.
Simply change the class to have getNext() to return a pointer (possibly the null pointer).
More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf
Premature optimization is the root of all evil --Donald E. Knuth
Bookmarks