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;
}
};
In a member function, you don’t generally need to use
thisto access class members; you can simply use:etc.
If you have function parameters or other local variables that have the same name as a class member variable, you can use
thisto refer to the member variable, e.g.,The reason that your code is illegal is that it does not correctly treat
leftas a pointer. You need to dereferenceleftusing->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 ofpostfix()(i.e., it dereferences whatever is returned bypostfix()).postfix()doesn’t return anything, so it’s an error. It is important to remember that the.and->operators both have higher precedence than*.