tags:

views:

154

answers:

3

I've written a member function of class Node to read a tree of Nodes in postfix order.

It will be called by the Node instance which is the root node of the tree.

So: N.postfix();

these appear to be illeagal:

*this->left.postfix();
*this->right.postfix();

What is the proper way to do this?

class Node
{
public:
    const char *cargo; 
    int depth; 
    Node *left; 
    Node *right

void Node::postfix()
{
    if (this==__nullptr)
    {
        return;
    }
    else
    {
        *this->left.postfix();
        *this->right.postfix();
        out<<*this->cargo<<"\n";
        return;
    }
};
+10  A: 

In a member function, you don't generally need to use this to access class members; you can simply use:

left->postfix();

etc.

If you have function parameters or other local variables that have the same name as a class member variable, you can use this to refer to the member variable, e.g.,

this->left->postfix();

The reason that your code is illegal is that it does not correctly treat left as a pointer. You need to dereference left using -> in order to access its members, as shown in the correct code here. (You could also use the equivalent (*left).postfix(), but that just makes you use more parentheses for no real benefit.)

The use of the indirection operator * at the start of the expression is also incorrect, because it is applied to the result of postfix() (i.e., it dereferences whatever is returned by postfix()). postfix() doesn't return anything, so it's an error. It is important to remember that the . and -> operators both have higher precedence than *.

James McNellis
+6  A: 

The -> operator dereferences a pointer, so the extra * will cause problems. You can either do this:

this->left->postfix();

Or this:

(*this).left->postfix();
Andy White
Thanks for the edit... I wasn't playing close enough attention.
Andy White
+1  A: 

*this->left.postfix();

"Dereference the return value of calling postfix() on the 'left' member variable of this."


this->left->postfix();
//or
(*this->left).postfix();

"Call postfix() on the dereferenced 'left' member variable of this."

Noah Roberts