开发者

Error Msg: cannot convert parameter 1 from 'Node *' to 'Node'

开发者 https://www.devze.com 2023-01-03 22:09 出处:网络
I\'m writing an expression tree. The Node class has instances of itself as members left, right and parent.

I'm writing an expression tree.

The Node class has instances of itself as members left, right and parent.

Thanks to James McNellis in this post, I declared them as pointers.

   class Node
   {
     public:
        char *cargo; 
        int depth; 
        Node *parent;
        Node *left; 
        Node *right;
    //constructors/destructor:
        Node(void); 
        Node(int a_depth, Node *pparent = __nullptr); 
        ~Node();
    //method:
        void traverse_tree(Node n)
    };

Now I try to traverse the tree and print it out (to file "out").

Recursively calling 'traverse_tree(left);' and 'traverse_tree(right);'

causes the error message "cannot convert parameter 1 from 'Node *' to 'Node'".

Traverse_tree is called initially with the root node as the arguement.

I think the declaration of the parameter "(Node n)" is confusing the compiler and it doesn't know

whether to call a constructor or not.

How do 开发者_JS百科I pass "left" and "right" to the "traverse_tree" method?

void Node::traverse_tree(Node n)
    //utility to view the tree
{
    if (((left) ==  __nullptr)||((right) ==  __nullptr))
    {
        return;
    }
    traverse_tree(right);
    out<<'  '<<n.cargo<<"\n";
    traverse_tree(left);
    return;
};


Dereference your pointers:

traverse_tree(*right);

You might also want to change your traverse_tree method to accept a reference:

void traverse_tree(Node &n)


I think you should be calling traverse_tree with a node pointer, not a node. You generally use pointers for this sort of operation. This would result in something like:

void Node::traverse_tree (Node *n) {
    if ((left == __nullptr) || (right == __nullptr))
        return;
    traverse_tree (right);
    out << "  " << n.cargo << "\n";
    traverse_tree (left);
    return;
};

and you would call it with:

root.traverse_tree (&root);

You may want to re-engineer your code at some point to make it more C++-like:

void Node::traverse_tree(void) {
    if ((left == __nullptr) || (right == __nullptr))
        return;
    right->traverse_tree();
    out << "  " << cargo << "\n";
    left->traverse_tree();
    return;
};

In other words, traverse using the methods of the sub-nodes themselves rather than passing the pointers (which is really the "old-school" non-object-oriented way of doing things).

0

精彩评论

暂无评论...
验证码 换一张
取 消