In my class, I have a member variable std::vector<node*> children
I want to overload the subscript operator so that I can easily index one of the nodes.
Here is my class deceleration for that function:
node* operator[](int index);
Here is my class definition for that function:
node* class_name::operator[](int index){
return children[index];
}
However, this function does not seem to return a pointer as I had hoped.
Here is the function that is giving me trouble:
void Print_Tree(node* nptr, unsigned int & depth){
if (NULL == nptr) {
return;
}
//node display code
for (int i = 0; i < nptr->Number_Of_Children(); ++i){
Print_Tree(nptr[i],depth+1); //<- Problem Here!
}
//node display code
return;
}
The error I get is:
error: cannot convert ‘node’ to ‘node*’ on the recursive call
I don’t understand why it gives me back a node when I want a pointer to a node.
Is there something wrong with my overloaded function?
I tried dereferencing the node in the recursive call:
Print_Tree(*nptr[i],depth+1);
Print_Tree(*(nptr[i]),depth+1);
Print_Tree(nptr->[i],depth+1);
to no avail!
What am I doing wrong?
Your are looking for the problem in the right place, but the syntax in your three correction attempts is still slightly wrong.
nptris a pointer to aNodeobject, so you cannot apply the index operator directly (if you do, the compiler will assume it points to the beginning of aNodearray and jump to the ith entry).Instead you need to first dereference the pointer, and then apply the index operator. Use parentheses to determine the order of this:
On a separate note, your using
intas the data type for the index into the vector is slightly incorrect. Better usestd::size_torstd::vector<Node*>::size_type.Furthermore, given that this question is tagged c++11, I should point out that the correct way to refer to the null pointer is
nullptr, notNULL.