[問題] ++ operator overloading
開發平台(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
05/11 21:10, 1F
→
05/11 21:13, , 2F
05/11 21:13, 2F
→
05/11 21:21, , 3F
05/11 21:21, 3F
→
05/11 21:27, , 4F
05/11 21:27, 4F
→
05/11 21:29, , 5F
05/11 21:29, 5F
→
05/11 21:30, , 6F
05/11 21:30, 6F
→
05/11 21:53, , 7F
05/11 21:53, 7F
→
05/11 21:54, , 8F
05/11 21:54, 8F
→
05/11 21:54, , 9F
05/11 21:54, 9F
→
05/12 11:18, , 10F
05/12 11:18, 10F
→
05/12 11:19, , 11F
05/12 11:19, 11F
→
05/12 11:20, , 12F
05/12 11:20, 12F
→
05/12 11:32, , 13F
05/12 11:32, 13F