Re: [問題] C++ 判斷是不是new出來的物件

看板C_and_CPP (C/C++)作者 (十三)時間14年前 (2011/09/22 23:33), 編輯推噓0(003)
留言3則, 1人參與, 最新討論串2/4 (看更多)
※ 引述《wagaru (wagaru)》之銘言: : 我現在有一個class Tree,有三個成員是pointer : 在copy時會new新的Tree : 在destructor裡我想delete這些new出來的tree : 因此我寫在解構式裡 : 但因為constructor 裡沒有用new,要delete用那種建構式建出的樹時就會出錯 : 請問是哪邊出問題了呢? 謝謝~ : (如果講的不清楚我之後再補充…) : ===================================================================== : class Tree{ : private: : std::string root; : Tree* left_child; : Tree* right_child; : public: : //copy constructor : Tree(const Tree& tree):left_child(0),right_child(0){ : if(tree.left_child != 0) : left_child = new Tree(*tree.getLeftChild()); : if(tree.right_child!= 0) : right_child = new Tree(*tree.getRightChild()); : } : //用下面這種建構式建出的樹 delete會出錯 : //constructor : Tree(std::string in_root, Tree &in_left, Tree &in_right): : root(in_root),left_child(&in_left),right_child(&in_right){} 這個是Tree還是Node啊?我不太清楚原po所定義的。 如果是 //constructor Tree(std::string in_root, Tree **in_left, Tree **in_right): root(in_root){ left_child = new Tree(**in_left); right_child = new Tree(**in_right); } 然後傳的話 Tree thisTree = new Tree(lastTree.getRoot(), &lastTree.getLeftChild(), ... 一行寫不下,後面類推了。 不曉得能否行得通。 : ~Tree(){ : if(left_child!=0) : delete left_child; : if(right_child!=0) : delete right_child; : } : } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.43.113.144 ※ 編輯: bleed1979 來自: 114.43.113.144 (09/22 23:51)

09/23 00:41, , 1F
其實就跟linked list裡的node很類似啦…XD
09/23 00:41, 1F

09/23 00:41, , 2F
我再試試原po的方法
09/23 00:41, 2F
※ 編輯: bleed1979 來自: 114.43.113.144 (09/23 00:44)

09/23 00:54, , 3F
為什麼要用**而不是&啊?
09/23 00:54, 3F
文章代碼(AID): #1EUrKrKO (C_and_CPP)
文章代碼(AID): #1EUrKrKO (C_and_CPP)