我做了一個MegaInt類,它可以處理非常大的數字並且重載了幾個運算符。不幸的是,我被卡住了,我的代碼崩潰了。在C++中重載運算符 - 編譯但崩潰
每個MegaInt OJB具有矢量值和一個布爾標誌。一個數的每個位置被放置在載體(即4325是矢量值= {5,2,3,4}),以及是否其符號(+或 - )爲1或0。
這裏有點的代碼...
#include <vector>
#include <string>
using namespace std;
class MegaInt{
friend class main;
private:
vector<int> value;
bool sign; //true is pos, false is neg
public:
MegaInt(vector <int> x, bool y);
MegaInt(string s);
MegaInt(const MegaInt& m);
MegaInt & operator*=(const MegaInt &rhs);
#include <iostream>
using namespace std;
#include "MegaInt.h"
#include <math.h>
MegaInt::MegaInt(string s){
int pos = s.length()-1;
while (pos >= 0){
if(pos == 0 && s[pos] == '-'){
sign = false;
break;
}
else if (pos == 0 && s[pos] == '+'){
sign = true;
break;
}
else{
sign = true;
}
if(s[pos] >= 48 && s[pos] <= 57)
value.push_back(s[pos]-48);
else{
value.clear();
break;
}
pos --;
}
chopoffleadingOs();
}
MegaInt::MegaInt(const MegaInt& m){
value = m.value;
sign = m.sign;
}
MegaInt operator*(const MegaInt& x, const MegaInt& y){
int multi = 0;
int temp;
vector<int> total;
for(int i = x.value.size()-1; i>=0; --i){
for(int j = y.value.size()-1, k = 0; j>=0; --j, ++k){
temp = x.value[i] * y.value[j];
if (total.size() <= (i + multi + 1))
total.resize(i + multi + 1 + 1);
total[i + multi] += (temp % 10);
temp = (temp - total[i])/10;
total[i + multi + 1] += temp;
}
multi++;
}
reverse(total.begin(), total.end());
return newTotal;
}
我主要似乎被卡在重載乘法部分。其餘的我認爲我得到了。
感謝, 諾亞
我剛剛改變了總數[i + multi] + =(8%10);總計[i + multi] + =(temp%10); – 2012-03-14 06:51:34
好吧生病嘗試 – 2012-03-14 06:52:00
@ Noah_noobProgrammer99我在回答中使用了錯誤的函數,它應該是'resize'而不是'reserve'。我已經更新了我的答案。 – 2012-03-14 07:02:25