2

我正在尝试实现自定义树结构,但我得到了一个奇怪的输出。

enum letter{B,A,T,G,C,N};
struct Node {
    int ltr;
    Node* ptr;
};
class GTree
{

public:
    GTree(int);
    void insert(int);
private:
    Node* root;
    void insert(int l,Node* leaf);
};
GTree::GTree(int l)
{
    root->ltr=l;
}
void GTree::insert(int l, Node *leaf)
{
    cout<<leaf->ltr;
}
void GTree::insert(int l)
{
    if(root==NULL)
    {
        insert(l, root);
    }
    else
    {
        root= new Node;
        insert(l,root);
    }
}
int main()
{
    GTree tree=GTree(T);
    tree.insert(T);
}

即使我期待 2,输出也显示为 -2062064467。这里发生了什么?我正在研究一个简单的 BTree 实现,但打算将其重新用于我想要的数据结构。

4

3 回答 3

6

首次创建 GTree 对象时,您没有创建 Node 对象。

GTree::GTree(int l)
{
    root->ltr=l;
}

应该

GTree::GTree(int l)
{
    root = new Node();
    root->ltr=l;
}

此外,请确保您有一个析构函数来清理资源。


我觉得我应该指出的另一件事是,它GTree::insert(int l, Node *leaf)可能不会像你期望的那样做。

cout<<leaf->ltr;

上面的代码只输出节点中的整数值,而不是实际分配它。

但也许你还没有完成那部分。:-)

于 2013-06-20T01:14:25.897 回答
2

您尚未初始化 root,因此root->ltr=l;会产生未定义的行为。先添加root = new Node();

于 2013-06-20T01:13:15.443 回答
0

我运行了您的代码并在 Ubuntu 12.04 上使用 gcc 4.6.3 获得了输出 0。

于 2013-06-20T01:20:49.647 回答