【问题标题】:constructor makes the object but doesn't assign values to it构造函数创建对象但不为其赋值
【发布时间】:2013-11-18 06:47:25
【问题描述】:

我正在编写一个二叉搜索树来保存多项式的值。我唯一的问题是制作一个带有 2 个参数(系数,x 的幂)的叶子。

    tree newTree(5,2)    ;5(x^2)
    tree anothertree()   ;it works then I can insert leaf into the root

构造函数生成根,但是当我想打印树时它是空的。

这是我的构造函数,它接受 2 个值来为树创建一个节点。

tree::tree(const int& c,const int& x)
{
    treeNode* root = new treeNode(c,x);
}

这是我用来为树创建节点的 Node 结构。

        struct treeNode
       {
        int x;
        int coef;
        treeNode* left;
        treeNode* right;
        treeNode()
        {
            this->x=0;
            this->coef=0;
            this->left=nullptr;
            this->right=nullptr;
        }
        treeNode(const int& c,const int& x)
        {
            this->x = x;
            this->coef = c;
            left = nullptr;
            right = nullptr;
        }
    };

这是我正在学习的课程:

 class tree{
    private:
    treeNode* root;
     void postorder(treeNode* p);
     void inorder(treeNode* p);
     void preorder(treeNode* p);
     void destroyTree(treeNode* p);
     void copyTree(treeNode* original,treeNode* &copycat);

public:
    tree();
    tree(const int& c,const int& x);
    tree(const tree& myTree);
    ~tree();
    void insert(int c,int xval);
    const tree & operator=(const tree &myTree);
    void print_postorder();
    void print_inorder();
    void print_preorder();
 };

【问题讨论】:

  • tree anothertree() ;it works - 嗯,这声明了一个返回tree,而不是tree 对象的函数。它真的如你所愿吗?
  • @Charles Bailey 它使默认树的根为空。

标签: c++ tree binary-search-tree


【解决方案1】:
tree::tree(const int& c,const int& x)
{
    treeNode* root = new treeNode(c,x);
}

root 将在您的构造函数完成后立即超出范围(并且会泄漏您刚刚分配的内存)。

您已将 treeNode* root; 声明为您的 tree 类的成员,您需要的是:

tree::tree(const int& c,const int& x)
{
    root = new treeNode(c,x);
}

或

tree::tree(const int& c,const int& x) : root(new treeNode(c,x))
{
}

注意:您还需要在析构函数中释放该内存,并且随时更改root 指向的内存位置。将其包裹在 std::shared_ptr 或 std::unique_ptr 中会是更好的解决方案。

【讨论】:

    【解决方案2】:

    构造函数退出后,root 将超出范围。

    你需要声明一个全局根指针并在你的构造函数中初始化它。

    【讨论】:

    • 它不需要是全局的。我认为他应该将其声明为树类的一部分。
    • 确实如此,关键是在构造函数调用之外持久化它
    猜你喜欢
    • 2015-08-18
    • 2016-09-23
    • 1970-01-01
    • 2013-04-05
    • 2019-11-02
    • 2013-09-24
    • 2012-02-05
    • 1970-01-01
    相关资源
    最近更新 更多