简体   繁体   中英

overload subscript operator does not return pointer

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.

nptr is a pointer to a Node object, so you cannot apply the index operator directly (if you do, the compiler will assume it points to the beginning of a Node array 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:

Print_Tree((*nptr)[i],depth+1);

On a separate note, your using int as the data type for the index into the vector is slightly incorrect. Better use std::size_t or std::vector<Node*>::size_type .


Furthermore, given that this question is tagged , I should point out that the correct way to refer to the null pointer is nullptr , not NULL .

Even though it is indeed legal to have operator[] return a pointer, it is better design (and fits expectations from standard classes) to return a reference instead. You can then take the address of that reference as follows:

node& class_name::operator[](int index){
    return *(children[index]);
}

and then use it as:

Print_Tree(&(*nptr)[i],depth+1);

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