Re: [問題] C++ 判斷是不是new出來的物件
※ 引述《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
09/23 00:41, 1F
→
09/23 00:41, , 2F
09/23 00:41, 2F
※ 編輯: bleed1979 來自: 114.43.113.144 (09/23 00:44)
→
09/23 00:54, , 3F
09/23 00:54, 3F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 4 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章
11
38