#include <iostream> #include <string> using namespace std; class TreeNode { public: TreeNode():count(0),left(0),right(0){cout<<"TreeNode()"<<endl;} //此处将构造left、right的初始化放在初始化列表中(即:left(new TreeNode(*lef),right(new TreeNode(*rig))为什么编译无法通过??? TreeNode(const string val,const int cnt,const TreeNode *lef,const TreeNode *rig):value(val),count(cnt) { left=new TreeNode(*lef); right=new TreeNode(*rig); cout<<"TreeNode(,,,)"<<endl; } TreeNode(const TreeNode& org); ~TreeNode(); string getValue(){return value;} private: string value; int count; TreeNode *left; TreeNode *right; }; TreeNode::TreeNode(const TreeNode& org) { cout<<"TreeNode(const TreeNode& org)"<<endl; count=org.count; if (org.left) { left=new TreeNode(*org.left); } else left=0; if (org.right) { right=new TreeNode(*org.right); } else right=0; } TreeNode::~TreeNode() { cout<<"~TreeNode"<<endl; if (left) { delete left; } if(right) { delete right; } } int main() { TreeNode tn; TreeNode left; TreeNode right; TreeNode root("root",1,&left,&right); }
问题如注释,求大神解答~~~~~~
为什么不能放在初始化列表中? 我试了下是能编译过的。
class TreeNode { public: TreeNode(const string val, const int cnt, const TreeNode *lef, const TreeNode *rig) : value(val), count(cnt), left(new TreeNode(*lef)), right(new TreeNode(*rig)) { cout << "TreeNode(,,,)" << endl; } TreeNode(const TreeNode& org); ~TreeNode(); private: string value; int count; TreeNode *left; TreeNode *right; };
left(new TreeNode(*lef),right(new TreeNode(*rig)) //拷贝你的代码
left(new //我写的代码
你不觉得你的括号有问题吗?比我的括号宽了点吗?
另外一点,在初始化列表里面调用new是相当糟糕的做法。因为new是会抛出异常的。就以你的为例,假如right(new TreeNode(*rig))抛出了异常,因为构造函数还没有被调用,自然就不会调用析构函数,这个时候left就造成了内存泄露了。