Re: [問題] 問一個物件相加 operator+ 的問題....

看板C_and_CPP (C/C++)作者 (米蟲)時間16年前 (2009/05/15 14:35), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/4 (看更多)
※ 引述《aquatear (米蟲)》之銘言: : 寫了一個重載 + 號 的函式 , 目的是將兩個 CWin 物件相加, : 此物件是一個視窗, 相加結果是取視窗最大的寬高當作新視窗的寬高, : 然後把新視窗的 title 設為 "new win" : CWin operator+(CWin &w) : { : int width,height; : width = this->width > w.width ? this->width: w.width; : height = this->height > w.height ? this->height : w.height; : return CWin(100,width,height,"new win"); : } hi! 上篇有人告訴我需要重載 "=" 運算子, 我覺得不需要 因為我以為 win1 = win2+win3; 在做完 win2+win3 時, 即 做完 operator+ 後, 會立刻把 operator+ 裡的 local 物件解構銷毀 其實不是這樣 事實上是 會做完 win1=win2+win3 整行敘述, 也就是做完 operator+ , operator= 才會呼叫解構將 operator+ 裡的物件銷毀 所以還是需要自己寫 operator= , 將 title 複製給 win3 這樣就沒問題了, 不過我覺得我的 operator= 寫得非常鳥 如下 CWin& operator=(CWin &w) { width = w.width; height = w.height; delete [] this->title; this->title = new char[strlen(w.title)+1]; strcpy(this->title,w.title); return *this; } 因為一開始建構就會有一個 default 字串所以必須先 delete 掉 再根據新的 "new win" 配記憶體並複製, 不曉得有沒有更簡潔的方法 感謝大家討論提供盲點 ! 有需要 source 我可以貼出所有 source 給大家研究 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.219.68.170
文章代碼(AID): #1A3Gr1lN (C_and_CPP)
文章代碼(AID): #1A3Gr1lN (C_and_CPP)