Re: [問題] 大數字加法

看板C_and_CPP作者 (燒賣)時間14年前 (2011/12/25 04:29), 編輯推噓3(3018)
留言21則, 6人參與, 最新討論串2/3 (看更多)
※ 引述《steve1012 (steve)》之銘言: : → PkmX:我猜應該是你沒寫copy constructor的問題 12/25 01:06 HugeInteger HugeInteger::Add( HugeInteger num2 ) { HugeInteger temporary; ... return temporary; } 這一行會隱含 copy construction。 temporary 在這個 function 結束之後就 destruct 了, 所以實質上會有另一個 compiler 自行加上的 temp 物件,相當於這樣: HugeInteger compiler_added_temp(temporary); temporary.~HugeInteger(); return compiler_added_temp; 因為沒有實作 copy contructor,預設的 copy contructor 是把 data member 逐一複製,於是 compiler_added_temp.IntegerArr == temporary.IntegerArr, 所以該陣列會被 delete 兩次。 題外話,你的程式碼變數/functon命名原則很凌亂...。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.250.29.121 ※ 編輯: freesamael 來自: 111.250.29.121 (12/25 04:36)

12/25 11:02, , 1F
真的是這樣 太感謝大大了!
12/25 11:02, 1F

12/25 11:03, , 2F
不好意思寫得很凌亂讓你們看得很累QQ
12/25 11:03, 2F

12/25 11:04, , 3F
另外可以請教一下為什麼會delete兩次嗎?
12/25 11:04, 3F

12/25 11:04, , 4F
我只有寫一個destructor而已~
12/25 11:04, 4F

12/25 11:05, , 5F
還有我命名不好的地方是function定義裡面的變數嗎
12/25 11:05, 5F

12/25 11:05, , 6F
還是整個class的function, variables的命名都不好?
12/25 11:05, 6F

12/25 11:35, , 7F
譬如說,為什麼Add, Subtract是大寫開頭,其他是小寫開頭
12/25 11:35, 7F

12/25 15:12, , 8F
簡而言之,記住 class 中使用 new 做動態記憶體配置的話
12/25 15:12, 8F

12/25 15:13, , 9F
最好把 constructer, copy constructer,
12/25 15:13, 9F

12/25 15:14, , 10F
assignment operator(operator=), destructor 都自己寫
12/25 15:14, 10F

12/25 15:14, , 11F
不要用預設的,以免發生沒考慮到的狀況
12/25 15:14, 11F

12/25 16:54, , 12F
一般來說變數也不使用大寫開頭,以區隔object和class
12/25 16:54, 12F

12/25 16:55, , 13F
例如 HugeInteger *hugeInteger = new HugeInteger();
12/25 16:55, 13F

12/25 16:55, , 14F
你的data member都是用大寫開頭的,function有大有小
12/25 16:55, 14F

12/25 16:56, , 15F
看起來比較凌亂。常見的data member命名法是加 m 或 _
12/25 16:56, 15F

12/25 16:56, , 16F
比如說 mIntegerArr 或 _integerArr
12/25 16:56, 16F

12/25 17:01, , 17F
_要加在後面,不要加在前面
12/25 17:01, 17F

12/25 17:52, , 18F
補充一下, WJ 說的這件事叫做 Rule of three
12/25 17:52, 18F

12/25 17:52, , 19F
"three" 即是指 copy ctor, operator = 和 dtor 三個成員
12/25 17:52, 19F

12/25 17:53, , 20F
只要其中一個是手動定義的 那有很大機會三個都要自己寫
12/25 17:53, 20F

12/25 22:30, , 21F
謝謝你們 真是太感謝你們了
12/25 22:30, 21F
文章代碼(AID): #1EzZOf3O (C_and_CPP)
討論串 (同標題文章)
本文引述了以下文章的的內容:
以下文章回應了本文
完整討論串 (本文為第 2 之 3 篇):
文章代碼(AID): #1EzZOf3O (C_and_CPP)