在我的程序中,有两个类Node和Tree。 树有一个数据成员Node *头。 我正在尝试使用重载的运算符=将一棵二叉树复制到另一棵二叉树 最后,当我在=函数中返回Tree对象时,它不会返回我的Tree对象。
这是我的Node类
class Node
{
char data;
Node *lchild, *rchild;
public:
Node( char data )
{
this->data = data;
lchild = NULL;
rchild = NULL;
}
Node* operator= ( Node &p )
{
cout << "HI2\n";
Node* q = new Node(p.data);
if( p.lchild == NULL )
q->lchild = NULL;
else
*q->lchild = *p.lchild;
if( p.rchild == NULL )
q->rchild = NULL;
else
*q->rchild = *p.rchild;
return q;
}
friend class Tree;
};
这是我的Tree类
class Tree{
Node *head = NULL;
public:
Tree()
{
head = NULL;
}
Tree( Node* h )
{
head = h;
}
char root()
{
return head->data;
}
Node* getHead()
{
return head;
}
Tree operator= ( Tree &t )
{
Tree s;
Node* p = t.getHead();
Node* q;
if( p != NULL )
{
q = new Node(p->data);
s.head = q;
if( p->lchild == NULL )
q->lchild = NULL;
else
{
*q->lchild = *p->lchild;
}
if( p->rchild == NULL )
q->rchild = NULL;
else
{
*q->rchild = *p->rchild;
}
}
//s.inorder(s.getHead());
return s;
}
void inorder( Node *temp )
{
if( temp != NULL )
{
inorder(temp->lchild);
cout << temp->data << " ";
inorder(temp->rchild);
}
}
};
这是我的main()
int main() {
Tree t,u;
string exp = "a*b/(c-d)+e*(f-g)";
t.createFromInfix(exp); //this function creates binary tree from infix expression
u = t;
u.inorder(u.getHead()); //this line does not get executed
return 0;
}
我没有得到任何输出
这是我完整代码的链接:https://pastebin.com/tM2Nh9Yi