我正在编写一个二叉搜索树来保存多项式的值。我遇到的唯一问题是制作一个带有 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* ©cat);
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_ptr
或 std::unique_ptr
中将是更好的解决方案。
关于c++ - 构造函数生成对象但不为其赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20037147/