c++ - 构造函数生成对象但不为其赋值

标签 c++ tree binary-search-tree

我正在编写一个二叉搜索树来保存多项式的值。我遇到的唯一问题是制作一个带有 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);
}

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

        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::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_ptrstd::unique_ptr 中将是更好的解决方案。

关于c++ - 构造函数生成对象但不为其赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20037147/

相关文章:

c++ - 检查 boost 定时线程是否已完成

javascript - Jquery 文件树 - 如何在文件夹单击时返回文件夹名称

c++ - 二叉搜索树实现。

c - BST 实现

c++ - auto_ptr.release() 中的段错误

c++ - 位域与位集

c++ - OpenCV 如何将 jpeg 图像缓冲区放入 cvShowImage

algorithm - 树可视化算法

c# - 使用 Roslyn 编译语法树

javascript - 在 Javascript 上显示二叉搜索树遍历(递归方式)