[問題] ++ operator overloading

看板C_and_CPP作者 (Veck)時間12年前 (2012/05/11 20:57), 編輯推噓0(0013)
留言13則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) 同樣是 operator overloading 的問題,不過這次是 ++ 的 postfix 無法正確傳入物件 BigInt::BigInt (const BigInt& original) //copy constructor { BigInt tmp; tmp.num = original.num; tmp.size = original.size; } BigInt::BigInt (const int* tmp, int length) { /* Convert an array of integral digits by tmp to BigInt * tmp: pointer to the array * length: the number of digits in the array */ this->size = length; this->num = new char[length]; for(int i=0;i<length;i++) this->num[i] = tmp[i]; } char &BigInt::operator[](int index) { /*Return the digits in char of a particular index*/ assert(index>=0 && index<size); return num[index]; } BigInt & BigInt::operator++() // for ++i (prefix) { num[size-1] += 1; for(int i=size-1; i>=0; i--) if(num[i]==58) { num[i] = '0'; num[i-1] = num[i-1] + 1; } else break; return *this; } BigInt BigInt::operator++(int) //for i++ (postfix) { BigInt tmp = *this; ++(*this); return tmp; } 以上我的 BigInt 程式碼實做部分,其成員有兩個 private: char* num; int size; 我發現我在 main 中建立了一個物件 bi, 並用建構子開了記憶體空間存放 num 當我呼叫 ++bi; 時是可以成功執行 但是 bi++; 就會當機 我去 trace 一下發現,雖然 bi++成功的進入 BigInt BigInt::operator++(int) 中 但是 *this 卻是錯誤的 (cout << this->num[0] << endl; 的結果不對) 請問該怎麼解決?我的問題在哪裡呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.170.225.18

05/11 21:10, , 1F
copy constructor 沒寫對
05/11 21:10, 1F

05/11 21:13, , 2F
我有試過改copy constructor 但還是不對,請問錯在哪呢?
05/11 21:13, 2F

05/11 21:21, , 3F
謝謝大大!!!! 原來是不用去在宣告一個 BigInt tmp !!!!
05/11 21:21, 3F

05/11 21:27, , 4F
不過回傳的好像還是不對...
05/11 21:27, 4F

05/11 21:29, , 5F
難道不是直接 num = original.num, size = original.size
05/11 21:29, 5F

05/11 21:30, , 6F
我怎覺得整份設計都有點怪怪的 Orz
05/11 21:30, 6F

05/11 21:53, , 7F
BigInt 有 [] 本來就很怪阿, 你有看過 int a; a[ 1 ];
05/11 21:53, 7F

05/11 21:54, , 8F
的用法嗎? operator overloading 要考慮到使用者預期
05/11 21:54, 8F

05/11 21:54, , 9F
的操作, 不是寫來自爽就好
05/11 21:54, 9F

05/12 11:18, , 10F
ctor我有遇過類似問題 試試this->num = original.num
05/12 11:18, 10F

05/12 11:19, , 11F
operator++()的for loop是不是很多餘?感覺怪怪的
05/12 11:19, 11F

05/12 11:20, , 12F
operator++(int)也怪怪的 ++(*this) then return tmp?
05/12 11:20, 12F

05/12 11:32, , 13F
++並不多餘,有問題的是 shallow copy/deep copy.
05/12 11:32, 13F
文章代碼(AID): #1FhGolg0 (C_and_CPP)